如何替换字符串的多个子字符串?我想使用.替换函数替换多个字符串。我现在string.replace("condition1", "")但我想要的是string.replace("condition1", "").replace("condition2", "text")虽然这感觉不像是好的语法做这件事的正确方法是什么?有点像grep/regex中你能做什么\1和\2将字段替换为某些搜索字符串
3 回答
![?](http://img1.sycdn.imooc.com/545847f50001126402200220-100-100.jpg)
慕雪6442864
TA贡献1812条经验 获得超5个赞
import re rep = {"condition1": "", "condition2": "text"} # define desired replacements here# use these three lines to do the replacementrep = 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 versionspattern = 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--'
![?](http://img1.sycdn.imooc.com/54586431000103bb02200220-100-100.jpg)
牛魔王的故事
TA贡献1830条经验 获得超3个赞
def replace_all(text, dic): for i, j in dic.iteritems(): text = text.replace(i, j) return text
text
dic
注iteritems()
items()
小心:
替换顺序无关 更换之前的替换结果是可以的
d = { "cat": "dog", "dog": "pig"}mySentence = "This is my cat and this is my dog."replace_all(mySentence, d)print(mySentence)
"This is my pig and this is my pig."
"This is my dog and this is my pig."
from collections import OrderedDictdef replace_all(text, dic): for i, j in dic.items(): text = text.replace(i, j) return text od = OrderedDict([("cat", "dog"), ("dog", "pig")])mySentence = "This is my cat and this is my dog."replace_all(mySentence, od) print(mySentence)
"This is my pig and this is my pig."
小心#2:text
![?](http://img1.sycdn.imooc.com/5458472300015f4702200220-100-100.jpg)
开心每一天1111
TA贡献1836条经验 获得超13个赞
repls = {'hello' : 'goodbye', 'world' : 'earth'}s = 'hello, world'reduce(lambda a, kv: a.replace(*kv), repls.iteritems(), s)
repls = ('hello', 'goodbye'), ('world', 'earth')s = 'hello, world'reduce(lambda a, kv: a.replace(*kv), repls, s)
添加回答
举报
0/150
提交
取消