【发布时间】:2018-07-31 02:50:33
【问题描述】:
给定字符串为:
s = "Python is programming language"
在此,我想用任何字符替换第二次出现的'n',比如说'o'。预期的字符串是:
"Python is programmiog language"
如何在 python 中做到这一点?我可以只使用replace 函数吗?或任何其他方式来做到这一点?
【问题讨论】:
给定字符串为:
s = "Python is programming language"
在此,我想用任何字符替换第二次出现的'n',比如说'o'。预期的字符串是:
"Python is programmiog language"
如何在 python 中做到这一点?我可以只使用replace 函数吗?或任何其他方式来做到这一点?
【问题讨论】:
您需要使用 maxreplace 参数调用str.replace()。对于仅替换字符串中的第一个字符,您需要将maxreplace 传递为1。例如:
>>> s = "Python is programming language"
>>> s.replace('n', 'o', 1)
'Pythoo is programming language'
# ^ Here first "n" is replaced with "o"
string.replace(s, old, new[, maxreplace])返回字符串
s的副本,其中所有出现的子字符串 old 都替换为new。 如果给定可选参数maxreplace,则替换第一个maxreplace 出现。
【讨论】: