2016-12-16 10 views
-1

私は「男が店に行った」という文章を持っています。「th」または「sh」を含む単語を「dog」と置き換えたいのですが、結果は次のようになります:複数の文字列を検索するにはどうしたらいいですか? (Python)

現在

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 

私はWANにdogse男が私のコードは、これまでにどのように見えるかこれはある

をdogsop dogseに行ってきましたこれだけを印刷する:

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 
関連する問題