string replace for back slash

Discussion in 'Python' started by rdmurray@bitdance.com, Feb 5, 2009.

  1. Guest

    "S.Selvam Siva" <> 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
    , Feb 5, 2009
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. AviraM
    Replies:
    2
    Views:
    6,332
    Manish Pandit
    Sep 28, 2006
  2. destroooooy
    Replies:
    4
    Views:
    645
    Arnaud Delobelle
    Apr 29, 2008
  3. andrew
    Replies:
    7
    Views:
    1,788
    Hillbilly
    Oct 9, 2008
  4. Chris Rebert

    Re: string replace for back slash

    Chris Rebert, Feb 5, 2009, in forum: Python
    Replies:
    0
    Views:
    411
    Chris Rebert
    Feb 5, 2009
  5. Replies:
    4
    Views:
    142
    Evertjan.
    Jun 26, 2004
Loading...

Share This Page