2017-10-15 6 views
0

pythonのreplaceメソッドを使わずに文中の単語を置き換える関数を書いていますが、問題は私のコードが言葉は別のものと結合し、たぶんおそらくすべてのものを置き換えると思われます。ある私のコードPythonのreplaceメソッドを使用せずに文中の単語を置き換える方法

def replace_all (target,find,replace): 
       split_target = target.split() 
       result = '' 
       for i in split_target: 
         if i == find: 
           i = replace 
         result += i + ' ' 
       return result.strip() 
      target = "Maybe she's born with it. Maybe it's Maybeline." 
      find = "Maybe" 
      replace = "Perhaps" 
      print replace_all(target, find, replace) 

出力を見てみましょう:

Perhaps she's born with it. Perhaps it's Maybeline. 

しかし、それは、この印刷することを期待しています:maybelineある最後の単語を変更することが想定される

Perhaps she's born with it. Perhaps it's perhapsline. 

お知らせおそらく線に。私は今一週間これと戦っています、どんな助けも高く評価されます。

+1

正規表現公正なゲームですか? –

答えて

3

の理由は、あなたが空白に分割しているので、あなたがfindiを比較しているとき、あなたはMaybeからMaybeline.を比較しているということです。それは一致しないので、あなたはその発生を置き換えていません。あなたがあなたの代わりに探している値でを分割して、置換文字列を持つ部品を結合する場合

は、あなたがMaybeがために使用される文字列、分割数を得るでしょう、そしてあなたは、これらに参加することができますそれらの間のreplace文字列で:

def replace_all (target,find,replace): 
    return replace.join(target.split(find)) 

target = "Maybe she's born with it. Maybe it's Maybeline." 
find = "Maybe" 
replace = "Perhaps" 

print(replace_all(target, find, replace)) 

> Perhaps she's born with it. Perhaps it's Perhapsline. 
関連する問題