2017-10-15 31 views
0

我已經寫了一個函數來替換句子中的單詞,而不使用替換方法中的python,問題是我的代碼在邊緣情況下失敗單詞與另一個詞相結合,我想可能會替換每一個可能的事件。看看我的代碼如何在不使用python替換方法的情況下替換句子中的單詞

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. 

,但我希望它打印:

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

公告的最後一句話是maybeline是假設改變或許線。我已經與此戰鬥了一週,任何幫助將不勝感激。

+1

是正則表達式公平遊戲嗎? –

回答

3

的原因是,你在拆分的空白,所以,當你比較ifind,你比較Maybeline.Maybe。這不匹配,所以你沒有取代那個事件。

如果您由你正在尋找替代的價值分裂,然後再加入與替換字符串的部分,你會得到一個數,其中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.