"S.Selvam Siva" <s.selvams...@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

Reply via email to