小编典典

Python-如何替换一个字符串的多个子字符串?

python

我想使用.replace函数替换多个字符串。

我目前有

string.replace("condition1", "")

但想有类似的东西

string.replace("condition1", "").replace("condition2", "text")

虽然那听起来不像是好的语法

正确的方法是什么?有点像如何在grep / regex中进行操作\1以及\2如何将字段替换为某些搜索字符串


阅读 1045

收藏
2020-02-09

共1个答案

小编典典

这是一个简短的示例,应该使用正则表达式来解决问题:

import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems()) 
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

例如:

>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")

’() and –text–‘

2020-02-09