2011-05-15 182 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事件。

相关问题