2011-05-15 196 views
25

我有這樣的事情:只替換一個字符串的第一次出現?

text = 'This text is very very long.' 
replace_words = ['very','word'] 

for word in replace_words: 
    text = text.replace('very','not very') 

我想只替換第一個「非常」或選擇其「非常」被覆蓋。我在更大量的文本上這樣做,所以我想控制如何替換重複的單詞。

回答

60
text = text.replace("very", "not very", 1) 

>>> help(str.replace) 
Help on method_descriptor: 

replace(...) 
    S.replace (old, new[, count]) -> string 

    Return a copy of string S with all occurrences of substring 
    old replaced by new. If the optional argument count is 
    given, only the first count occurrences are replaced. 
11
text = text.replace("very", "not very", 1) 

第三個參數是要替換出現的最大數量。
the documentation for Python

與string.replace(S,舊,新[,maxreplace])
返回字符串s的通過更換新的舊的子串出現的所有副本。如果給出可選參數maxreplace,則會替換第一個maxreplace事件。

相關問題