【问题标题】:Replace first occurrence only of a string?仅替换第一次出现的字符串?
【发布时间】:2026-01-23 07:00:02
【问题描述】:
我有这样的事情:
text = 'This text is very very long.'
replace_words = ['very','word']
for word in replace_words:
text = text.replace('very','not very')
我只想替换第一个“非常”或选择覆盖哪个“非常”。我正在对大量文本执行此操作,因此我想控制如何替换重复的单词。
【问题讨论】:
标签:
python
string
replace
【解决方案1】:
text = text.replace("very", "not very", 1)
第三个参数是要替换的最大出现次数。
来自the documentation for Python:
string.replace(s, old, new[, maxreplace])
返回字符串 s 的副本,其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数 maxreplace,则替换第一个 maxreplace 出现。
【解决方案3】:
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.