仅替换字符串的第一个匹配项?

我有这样的东西:

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


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

我想只替换第一个“ very”或选择哪个“ very”被覆盖。我在大量的文本上做这个操作,所以我想控制如何替换重复的单词。

97539 次浏览
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.

From http://docs.python.org/release/2.5.2/lib/string-methods.html :

replace( old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

I didn't try but I believe it works

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

The third parameter is the maximum number of occurrences that you want to replace.
From the documentation for Python:

string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.