如何在字符串中搜索多个字符串,然后用其他字符串替换它们? (蟒蛇)

时间:2016-12-16 13:49:21

标签: python string replace

我有以下句子“男人去了商店”,我想用“狗”取代任何带有“th”或“sh”的单词。结果看起来应该是这样的:

狗人去了dogse dogop

这是我的代码到目前为止的样子:

sentence = "the man went to the shop"

to_be_replaced = ["th", "sh"]
replaced_with = "dogs"

for terms in to_be_replaced:
    if terms in sentence:
        new_sentence = sentence.replace(terms,replaced_with)
        print new_sentence

目前,这会打印:

dogse man went to dogse shop
the man went to the dogsop

我希望它只打印这个:

dogse man went to dogse dogsop

我会这样做吗?

3 个答案:

答案 0 :(得分:4)

这应该有效:

failedMessage

答案 1 :(得分:1)

您只需从头开始处理相同的字符串并继续处理它。你不需要你的new_sentence(除非你想保留第一个)。

此代码应该有效:

<h:inputTextarea rows="5" cols="70" value="#{ticketBean.ticket.descripcio}" >
</h:inputTextarea>

应该打印:

sentence = "the man went to the shop"

to_be_replaced = ["th", "sh"]
replaced_with = "dogs"

for terms in to_be_replaced:
    if terms in sentence:
        sentence = sentence.replace(terms,replaced_with)
print sentence

答案 2 :(得分:1)

import re

text = "the man went to the shop"
repalceed = re.sub(r'sh|th', 'dogs', text)
print(repalceed)

出:

dogse man went to dogse dogsop