这是一个简短的示例,应该使用正则表达式来解决问题:
import rerep = {"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–‘



