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

Kir*_*til 1 python string

给定字符串为:

s = "Python is programming language"
Run Code Online (Sandbox Code Playgroud)

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

"Python is programmiog language"
Run Code Online (Sandbox Code Playgroud)

如何在 python 中做到这一点?replace我可以只使用函数来完成吗?或任何其他方式来做到这一点?

Moi*_*dri 5

需要str.replace()maxreplace参数调用。对于仅替换字符串中的第一个字符,您需要传递maxreplaceas 1。例如:

>>> s = "Python is programming language"
>>> s.replace('n', 'o', 1)
'Pythoo is programming language'
#     ^ Here first "n" is replaced with "o"
Run Code Online (Sandbox Code Playgroud)

str.replace文件中:

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

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