如何使用reg.expression用模式替换字符串

时间:2018-02-20 13:29:12

标签: python python-3.x regex-group

我有一个地址列表:

addr = ['100 NORTH MAIN ROAD',
            '100 BROAD ROAD APT.',
            'SAROJINI DEVI ROAD',
            'BROAD AVENUE ROAD']

我需要在以下功能中进行替换工作:

def subst(pattern, replace_str, string):

通过定义此函数外部的模式并将其作为参数传递给subst。

我需要一个输出:

addr = ['100 NORTH MAIN RD',
            '100 BROAD RD APT.',
            'SAROJINI DEVI RD ',
            'BROAD AVENUE RD']

其中所有'ROAD'字符串都替换为'RD'

def subst(pattern, replace_str, string):
  #susbstitute pattern and return it
  new=[]
  for x in string:
    new.insert((re.sub(r'^(ROAD)','RD',x)),x)
  return new

def main():
  addr = ['100 NORTH MAIN ROAD',
        '100 BROAD ROAD APT.',
        'SAROJINI DEVI ROAD',
        'BROAD AVENUE ROAD']

  #Create pattern Implementation here 
  pattern=r'^(ROAD)'
  print (pattern)
  #Use subst function to replace 'ROAD' to 'RD.',Store as new_address
  new_address=subst(pattern,'RD',addr)
  return new_address

我已经完成了这个并且低于错误

追踪(最近一次呼叫最后一次):

文件“python”,第23行,in   在主文件中输入“python”,第20行   文件“python”,第7行,在

TypeError:'str'对象不能解释为整数

4 个答案:

答案 0 :(得分:2)

不需要正则表达式,只需使用replace

[x.replace('ROAD', 'RD') for x in addr]

如果您只想将ROAD替换为单词,请不要在中间使用:

[re.sub(r'\bROAD\b', 'RD', x) for x in addr]

答案 1 :(得分:0)

使用re

import re
addr = ['100 NORTH MAIN ROAD',
            '100 BROAD ROAD APT.',
            'SAROJINI DEVI ROAD',
            'BROAD AVENUE ROAD']

for i, v in enumerate(addr):
    addr[i] = re.sub('ROAD', 'RD', v) #v.replace("ROAD", "RD")

print addr

<强>输出

['100 NORTH MAIN RD', '100 BRD RD APT.', 'SAROJINI DEVI RD', 'BRD AVENUE RD']

答案 2 :(得分:0)

使用 RegEx ..

from module1 import A
from module2 import B

答案 3 :(得分:0)

我得到了答案,

pattern=r'\bROAD\b'

将此参数传递给

def subst(pattern, replace_str, string):

    #susbstitute pattern and return it
    new=[re.sub(pattern,'RD',x) for x in string]
    return new

我们可以得到op:)