仅替换第一次出现的字符串?


75

我有这样的事情:

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

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

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


Answers:


119
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.

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

第三个参数是您要替换的最大出现次数。
Python文档中

string.replace(s,old,new [,maxreplace])
返回字符串s的副本,其中所有出现的子字符串old都被new替换。如果给出了可选参数maxreplace,则替换第一个出现的maxreplace。


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.