如何替换字符串中的多个子串?

469 投票
28 回答
819285 浏览
提问于 2025-04-16 18:16

我想用 .replace 函数来替换多个字符串。

我现在有

string.replace("condition1", "")

但我想要的是这样的

string.replace("condition1", "").replace("condition2", "text")

虽然这样写感觉语法不太对

那正确的做法是什么呢?有点像在 grep/正则表达式中,你可以用 \1\2 来替换特定的搜索字符串

28 个回答

179

为什么不采用像这样的单一解决方案呢?

s = "The quick brown fox jumps over the lazy dog"
for r in (("brown", "red"), ("lazy", "quick")):
    s = s.replace(*r)

#output will be:  The quick red fox jumps over the quick dog
194

你可以写一个简单的循环函数来处理这个问题。

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 的字典在遍历时没有可靠的顺序。这个解决方案只有在以下情况下才能解决你的问题:

  • 替换的顺序不重要
  • 替换可以改变之前替换的结果

更新:关于插入顺序的说法在 Python 3.6 及以上版本中不适用,因为标准字典已经改为使用插入顺序进行遍历。

举个例子:

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

可能的输出 #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")])
my_sentence = "This is my cat and this is my dog."
replace_all(my_sentence, od)
print(my_sentence)

输出:

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

小心 #2: 如果你的 text 字符串太大或者字典里的对数很多,这种方法会效率低下。

379

这里有一个简单的例子,可以用正则表达式来解决问题:

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--'

撰写回答