[Python-Dev] Inconsistent string.replace() behavior

Guido van Rossum guido@digicool.com
Wed, 09 May 2001 21:12:55 -0500


> test_strop.py contains this line:
> 
>     test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 0)
> 
> string_tests.py has this:
> 
>     test('replace', 'one!two!three!', 'one!two!three!', '!', '@', 0)
> 
> IOW, the test suite insists that
> 
>     strop.replace('one!two!three!', '!', '@', 0)
> 
> replace all matches but that
> 
>     string.replace('one!two!three!', '!', '@', 0)
> and
>     'one!two!three!'.replace('!', '@', 0)
> 
> replace nothing.
> 
> I've been thrashing like a madman trying to fix a common bug in both modules
> (in out-of-synch copies of mymemreplace), and every time I think I fix
> something "the other" module breaks.  The above appears to be why.
> 
> My opinion:  the test_strop.py test is in error, and so was strop_replace()
> in stropmodule.c.  I'm checking in changes accordingly, but won't mind
> getting yelled at if you disagree.

HMMMMMM!  In Python 1.5, a count of zero always replaces all
occurrences, both using string and using strop.  In 2.0 and later,
strop's replace(..., 0) still replaces all, but string's replaces
none.  The replace() method of strings and unicode objects agrees with
string.py.

I think this change was made in the sake of ease of documenting the
behavior: special-casing the count of zero is unexpected.

I very vaguely recall that it was discussed on this list.

So this suggests that test_string is correct, and string.replace()
(and the methods) shouldn't be "fixed"!

But since we're not really supporting strop any more, I think that
strop shouldn't be changed either.  So we'll have to live with the
difference -- sorry!

--Guido van Rossum (home page: http://www.python.org/~guido/)