我想用RD代替ROAD
addr = ['100 NORTH MAIN ROAD',
'100 BROAD ROAD APT.',
'SAROJINI DEVI ROAD',
'BROAD AVENUE ROAD']
输出
output : ['100 NORTH MAIN RD.',
'100 BROAD RD. APT.',
'SAROJINI DEVI RD.',
'BROAD AVENUE RD.']
我尝试了下面提到的代码
new_address=[word.replace("ROAD","RD") for word in addr]
但未获得所需的输出(BROAD也正在被RD取代。)
['100 NORTH MAIN RD.', '100 BRD. RD. APT.', 'SAROJINI DEVIRD.', 'BRD. AVENUE RD.']
答案 0 :(得分:0)
在此当前示例中可以执行以下操作:
new_address=[word.replace(" ROAD"," RD.") for word in addr]
或者通常使用regex
:
new_address = [re.sub(r'\bROAD\b', 'RD.', w) for w in l]
# ['100 NORTH MAIN RD.', '100 BROAD RD. APT.', 'SAROJINI DEVI RD.',
# 'BROAD AVENUE RD.']