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

2024-04-24 22:46:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我现在有

string.replace("condition1", "")

但我想喝点

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

尽管那感觉语法不太好

正确的方法是什么?类似于在grep/regex中,您可以通过\1\2将字段替换为某些搜索字符串


Tags: 方法函数字符串textstring语法grepreplace
3条回答

下面是一个简单的例子,它应该可以实现正则表达式的功能:

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

为什么没有这样的解决方案?

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

你可以做一个很好的循环函数。

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"}
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字符串太大或字典中有许多对,则效率低下。

相关问题 更多 >