如何替换字符串中第一次出现的字符?

时间:2018-02-20 16:56:31

标签: python string

给出字符串:

s = "Python is programming language"

在此,我想用任何字符替换第二次出现的'n',让我们说'o'。预期的字符串是:

"Python is programmiog language"

如何在python中执行此操作?我可以只使用replace功能吗?或其他任何方式吗?

1 个答案:

答案 0 :(得分:3)

您需要使用 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"

来自str.replace document

  

<强> string.replace(s, old, new[, maxreplace])

     

返回字符串s的副本,其中所有出现的子字符串old都替换为new如果给出了可选参数maxreplace,则会替换第一个maxreplace事件。

相关问题