string replace for back slash

Chris Rebert clp2 at rebertia.com
Thu Feb 5 06:59:16 EST 2009


On Thu, Feb 5, 2009 at 3:40 AM, S.Selvam Siva <s.selvamsiva at gmail.com> wrote:
> Hi all,
>
> I tried to do a string replace as follows,
>
>>>> s="hi & people"
>>>> s.replace("&","\&")
> 'hi \\& people'
>>>>
>
> but i was expecting 'hi \& people'.I dont know ,what is something different
> here with escape sequence.

The Python interactive interpreter does an implicit repr() (consult
the docs if you're unfamiliar with the repr() function) on the return
value of the expression. Note the single quotes in the output, which
obviously wouldn't be present in the string itself; same thing with
the doubling of the backslash.
If you instead do `print s.replace("&","\&")`, you'll see that the
outputted string does indeed only contain 1 backslash.

It's a common newbie confuser, there really should be a FAQ about it;
pity there isn't.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list