【问题标题】:How to replace first occurrence of character in a string? [duplicate]如何替换字符串中第一次出现的字符? [复制]
【发布时间】:2018-07-31 02:50:33
【问题描述】:

给定字符串为:

s = "Python is programming language"

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

"Python is programmiog language"

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

【问题讨论】:

    标签: python string


    【解决方案1】:

    您需要使用 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 出现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 2012-06-09
      • 2016-12-19
      • 2011-08-25
      相关资源
      最近更新 更多