Re: string replace for back slash

Discussion in 'Python' started by Chris Rebert, Feb 5, 2009.

  1. Chris Rebert

    Chris Rebert Guest

    On Thu, Feb 5, 2009 at 3:40 AM, S.Selvam Siva <> 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
     
    Chris Rebert, 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,399
    Manish Pandit
    Sep 28, 2006
  2. destroooooy
    Replies:
    4
    Views:
    659
    Arnaud Delobelle
    Apr 29, 2008
  3. andrew
    Replies:
    7
    Views:
    1,802
    Hillbilly
    Oct 9, 2008
  4. Replies:
    0
    Views:
    2,036
  5. Replies:
    4
    Views:
    152
    Evertjan.
    Jun 26, 2004
Loading...

Share This Page