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


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


方法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())
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--'

方法2-使用循环

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

在哪里text是完整的字符串,dic是一个字典 - 每个定义都是一个字符串,将替换该术语的匹配。

注意: 在Python 3中,iteritems()已被替换为items()

小心: Python字典没有可靠的迭代顺序。此解决方案仅解决您的问题,如果:

  • 替换顺序无关紧要
  • 更换可以更改以前更换的结果

例如:

d = { "cat": "dog", "dog": "pig"}
mySentence = "This is my cat and this is my dog."
replace_all(mySentence, d)
print(mySentence)

可能的输出#1:

"This is my pig and this is my pig."

可能的输出#2

"This is my dog and this is my pig."

一种可能的解决方法是使用OrderedDict

from collections import OrderedDict
def 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."