string.replace() question
Terry Hancock
hancock at anansispaceworks.com
Tue Jan 7 04:13:53 EST 2003
Per Jensen wrote:
> The Python doc on string.replace says this:
>
> replace(str, old, new[, maxsplit])
> """Return a copy of string str with all occurrences of substring old
> replaced by new. If the optional argument maxsplit is given,
> the first maxsplit occurrences are replaced."""
>
> I must have a blind spot, but the method doesn't seem to work quite like
> that. Example:
>
> bash-2.05$ python
> Python 2.2.1 (#1, Sep 24 2002, 21:50:51)
> [GCC 2.95.3 20010315 (SuSE)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import string
>>>> string.replace("C:\py21\gallery\resized", "\\", "/")
> 'C:/py21/gallery\resized'
>>>>
>
> Notice that the last "\" is not replaced with a "/"
>
> My question is why ?
See if this exercise makes any lights come on:
>>> s = "C:\py21\gallery\resized"
>>> print s
esized1\gallery
>>> s = r"C:\py21\gallery\resized"
>>> print s
C:\py21\gallery\resized
>>> s
'C:\\py21\\gallery\\resized'
>>> string.replace(s, "\\", "/")
'C:/py21/gallery/resized'
The problem is that the string you are operating on is not the one you
think it is. "\r" is a carriage return control character, not "\\" + "r" .
Cheers,
Terry
--
Anansi Spaceworks
http://www.anansispaceworks.com
More information about the Python-list
mailing list