2016-12-16 85 views
-1

我有以下句子“该男子去了商店”,我想用“狗”替换任何带有“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 

我会去做这件事吗?

+0

不是最好的实现,但它会工作,如果你重新绑定到'句子';将'new_sentence'改为'sentence' –

回答

1

你只需要从一开始就相同的字符串工作,坚持工作。你不需要你的new_sentence(除非你想保留第一个)。

此代码应工作:

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 

它应该打印:

dogse man went to dogse dogsop 
4

这应该工作:

s.replace("th", "dogs").replace("sh", "dogs") 
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 
相关问题