python中,replace函数默认是替换所有的匹配项
例如:
a = '22222'
b = a.replace('2', '3')
print(b)
但有时候可能只想替换其中的第一个匹配项或前几个匹配项,该如何设置呢?
这就需要重新看一下replace函数的官方定义说明
>>> 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.
会发现其中第三个可选的参数count代表了前几个匹配项需要被替换,所以把count设置为1,那么就只会替换第一个匹配项了。
例如:
a = '22222'
b = a.replace('2', '3', 1)
print(b)