如何替換字符串的多個子字符串?我想使用.替換函數(shù)替換多個字符串。我現(xiàn)在string.replace("condition1", "")但我想要的是string.replace("condition1", "").replace("condition2", "text")雖然這感覺不像是好的語法做這件事的正確方法是什么?有點像grep/regex中你能做什么\1和\2將字段替換為某些搜索字符串
3 回答

慕雪6442864
TA貢獻1812條經(jīng)驗 獲得超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--'

牛魔王的故事
TA貢獻1830條經(jīng)驗 獲得超3個贊
def replace_all(text, dic): for i, j in dic.iteritems(): text = text.replace(i, j) return text
text
dic
注iteritems()
items()
小心:
替換順序無關(guān) 更換之前的替換結(jié)果是可以的
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

開心每一天1111
TA貢獻1836條經(jīng)驗 獲得超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
提交
取消