[issue39304] Don't accept a negative number for the count argument in str.replace(old, new[, count])

Steven D'Aprano report at bugs.python.org
Sat Jan 11 10:57:54 EST 2020


Steven D'Aprano <steve+python at pearwood.info> added the comment:

This behaviour that goes all the way back to Python 1.5, if not older, before strings even had methods:

    [steve at ando ~]$ python1.5
    Python 1.5.2 (#1, Aug 27 2012, 09:09:18)  [GCC 4.1.2 20080704 
    (Red Hat 4.1.2-52)] on linux2
    Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
    >>> import string
    >>> string.replace("abacadaeaf", "a", "Z", -1)
    'ZbZcZdZeZf'


Hiding the fact that str.replace treats negative values as "replace all" just causes confusion, as people wrongly jump to the conclusion that it is a bug.

It's not a bug, it is a useful feature and it has been in the language for over 20 years. VB.Net has the same feature:

https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.strings.replace?view=netframework-4.8

Let's just document it as intentional and be done with it.

----------
nosy: +steven.daprano

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39304>
_______________________________________


More information about the Python-bugs-list mailing list