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

新手上路,请多包涵

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

我目前有

string.replace("condition1", "")

但想要有类似的东西

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

虽然这感觉不像是好的语法

这样做的正确方法是什么?有点像在 grep/regex 中你可以做 \1\2 将字段替换为某些搜索字符串

原文由 CQM 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 559
2 个回答

这是一个简短的例子,应该用正则表达式来解决这个问题:

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

原文由 Andrew Clark 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以做一个漂亮的小循环函数。

 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 字典没有可靠的迭代顺序。此解决方案仅在以下情况下解决您的问题:

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

更新:上述与插入顺序相关的声明不适用于大于或等于 3.6 的 Python 版本,因为标准字典已更改为使用插入顺序进行迭代。

例如:

 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:

 “这是我的猪,这是我的猪。”

可能的输出 #2

 “这是我的狗,这是我的猪。”

一种可能的解决方法是使用 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 字符串太大或字典中有很多对,则效率低下。

原文由 Joe Hansen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题