string.replace() question

Gerhard Häring gerhard.haering at opus-gmbh.net
Tue Jan 7 04:03:34 EST 2003


Per Jensen <per at net-es.dk> 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 ?

The backslash is an escape character. Inserting it like this might work, or
again it might not if the following character has a special meaning when
escaped with the backslash, and 'r' is among these.

The solution is to either always escape backslashes with an additional
backslash, so

>>> string.replace("C:\py21\gallery\resized", "\\", "/")

becomes

>>> string.replace("C:\\py21\\gallery\\resized", "\\", "/")

or you can use raw strings (r"..."):

>>> string.replace(r"C:\py21\gallery\resized", "\\", "/")

HTH,

Gerhard
-- 
Gerhard Häring
OPUS GmbH München
Tel.: +49 89 - 889 49 7 - 32
http://www.opus-gmbh.net/




More information about the Python-list mailing list