[Python-Dev] replace on empty strings (original) (raw)

Tim Peters tim.peters at gmail.com
Thu May 25 03:33:11 CEST 2006


[/F]

so, which one is correct ?

Python 2.4.3 >>> "".replace("", "a") '' >>> u"".replace(u"", u"a") u'a'

[Greg Ewing]

Probably there shouldn't be any "correct" in this case, i.e. the result of replacing an empty string should be undefined (because any string contains infinitely many empty substrings).

Where are they? For a string s, I count s[0:0], s[1:1], ..., s[len(s):len(s)], or len(s)+1 empty substrings in all.

While str and unicode replace currently disagree about that when len(s)==0, they agree when len(s)>0:

" ".replace("", "A") 'A A' u" ".replace("", "A") u'A A'

+0 on raising an exception if you try.

I'd be +1, except the idea that there are len(s)+1 empty substrings in a string is pretty much ubiquitous:

"" in "" True u"" in u"" True "".index("") 0 u"".index(u"") 0 " ".rindex("") 1 u" ".rindex(u"") 1 "".count("") 1 u"".count(u"") 1 " ".count("") 2 u" ".count(u"") 2

So the current str.replace really is an oddball.



More information about the Python-Dev mailing list