Is It Bug?

Tim Roberts timr at probo.com
Sun Dec 8 07:53:37 CET 2013


Mahan Marwat <mahanmarwat at gmail.com> wrote:
>
>Why this is not working.
>
>>>> 'Hello, \\\\World'.replace('\\', '\\')
>
>To me, Python will interpret '\\\\' to '\\'. 

It's really important that you think about the difference between the way
string literals are written in Python code, and the way the strings
actually look in memory.

The Python literal 'Hello, \\\\World' contains exactly 2 backslashes.  We
have to spell it with 4 backslashes to get that result, but in memory there
are only two.

Similarly, the Python literal '\\' contains exactly one character.

So, if your goal is to change 2 backslashes to 1, you would need
    'Hello, \\\\World'.replace('\\\\','\\')

However, REMEMBER that if you just have the command-line interpreter echo
the result of that, it's going to show you the string representation, in
which each backslash is shown as TWO characters.  Observe:

    Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit
(Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> s = 'Hello, \\\\World'
    >>> s
    'Hello, \\\\World'
    >>> print s
    Hello, \\World
    >>> s = s.replace('\\\\','\\')
    >>> s
    'Hello, \\World'
    >>> print s
    Hello, \World
    >>>
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list