【问题标题】:What happens when the third str.replace() parameter is negative?当第三个 str.replace() 参数为负时会发生什么?
【发布时间】:2020-11-17 16:48:42
【问题描述】:

请解释一下这里发生了什么?

print("banana".replace('a','1',-3))

输出是: b1n1n1

【问题讨论】:

  • 负数全部替换。这里有一些讨论:bugs.python.org/issue39304
  • 它正在取代一切。为什么你对正在发生的事情感到困惑?

标签: python python-3.x replace str-replace


【解决方案1】:

根据Ticket 5416

负值在某种程度上被用作标记值来表示全部替换。

【讨论】:

    【解决方案2】:

    根据文档https://docs.python.org/3/library/stdtypes.html#str.replace,代码应该只对第一个(计数)事件起作用。当count为负数时,这个规范是没有意义的,所以结果基本上只是一个实现细节。

    str.replace(old, new[, count]) 返回所有字符串的副本 子字符串 old 的出现被 new 替换。如果可选参数 count 是给定的,只有第一个 count 出现被替换。

    在 CPython 中,文档字符串说

        """
        Return a copy with all occurrences of substring old replaced by new.
        
          count
            Maximum number of occurrences to replace.
            -1 (the default value) means replace all occurrences.
        
        If the optional argument count is given, only the first count occurrences are
        replaced.
        """
    

    他们可能正在检查替换的东西的数量是否等于您的计数,方法是从您提供的数字中减少计数,直到它达到 0。如果您从 -1 或任何负数开始,内部计数器将永远不会达到 0,所以在 CPython 中,任何负数实际上意味着“全部替换”。

    【讨论】:

    • 嗯,还有更多内容,如问题 cmets 中发布的链接中所述,特别是 this part
    猜你喜欢
    • 2013-07-29
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 2015-01-15
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多