我有以下句子“该男子去了商店”,我想用“狗”替换任何带有“th”或“sh”的单词。结果应该是这样的:如何搜索多个字符串的字符串,然后用其他字符串替换它们? (Python)
dogse人去dogse dogsop
这是我的代码看起来像至今:
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
余万t它只打印此:
dogse man went to dogse dogsop
我会去做这件事吗?
不是最好的实现,但它会工作,如果你重新绑定到'句子';将'new_sentence'改为'sentence' –