我有这样的事情:

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

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

我只想替换第一个“非常”或选择哪个“非常”被覆盖。我正在处理大量文本,因此我想控制重复单词的替换方式。

最佳答案

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.

10-08 02:53