string replace for back slash

S.Selvam Siva s.selvamsiva at gmail.com
Thu Feb 5 08:48:11 EST 2009


On Thu, Feb 5, 2009 at 5:59 PM, <rdmurray at bitdance.com> wrote:

> "S.Selvam Siva" <s.selvamsiva at gmail.com> wrote:
> > 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.
>
> You are running into the difference between the 'repr' of a string (which
> is what is printed by default at the python prompt) and the actual
> contents of the string.  In the repr the backslash needs to be escaped
> by prefixing it with a backslash, just as you would if you wanted to
> enter a backslash into a string in your program.  If you print the string,
> you'll see there is only one backslash.  Note that you didn't need to
> double the backslash in your replacement string only because it wasn't
> followed by a character that forms an escape...but the repr of that
> string will still have the backslash doubled, and that is really the
> way you should write it in your program to begin with for safety's sake.
>
> Python 2.6.1 (r261:67515, Jan  7 2009, 17:09:13)
> [GCC 4.3.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> s="hi & people"
> >>> replacementstring = "\&"
> >>> replacementstring
> '\\&'
> >>> print replacementstring
> \&
> >>> x = s.replace("&","\\&")
> >>> x
> 'hi \\& people'
> >>> print x
> hi \& people
>
> --
> http://mail.python.org/mailman/listinfo/python-list



Thank you all for your response,

Now i understood the way python terminal expose '\'.



-- 
Yours,
S.Selvam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090205/e4f75979/attachment-0001.html>


More information about the Python-list mailing list