【发布时间】:2017-05-02 08:06:31
【问题描述】:
我有以下句子“那个人去了商店”,我想用“狗”替换任何有“th”或“sh”的单词。结果应该是这样的:
dogse man 去 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
我希望它只打印这个:
dogse man went to dogse dogsop
我会这样做吗?
【问题讨论】:
-
不是最好的实现,但如果你重新绑定到
sentence,它会起作用;将new_sentence更改为sentence