Python-如何替换一个字符串的多个子字符串?
发布于 2021-02-02 23:23:01
我想使用.replace
函数替换多个字符串。
我目前有
string.replace("condition1", "")
但想有类似的东西
string.replace("condition1", "").replace("condition2", "text")
虽然那听起来不像是好的语法
正确的方法是什么?有点像如何在grep / regex
中进行操作\1以及\2如何将字段替换为某些搜索字符串
关注者
0
被浏览
144
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–‘