【发布时间】:2020-06-16 05:19:22
【问题描述】:
我有以下字符串并列出“changewords”。我想将 '{word from list} \n' 替换为 '{word from list}:' 我不想替换 '\n' 的所有实例。
string = "Foo \n value of something \n Bar \n Another value \n"
changewords = ["Foo", "Bar"]
期望的输出:
'Foo: value of something \n Bar: Another value \n'
我已经尝试了以下
for i in changewords:
tem = re.sub(f'{i} \n', f'{i}:', string)
tem
Output: 'Foo \n value of something \n Bar: Another value \n'
和
changewords2 = '|'.join(changewords)
tem = re.sub(f'{changewords2} \n', f'{changewords2}:', string)
tem
Output: 'Foo|Bar: \n value of something \n Foo|Bar: Another value \n'
我怎样才能得到我想要的输出?
【问题讨论】:
-
可能也想查看其他答案@RohanGupta。一些示例更多地显示了 reg expr 的意图可以做什么。否则,还不如直接使用
"".replace()。