Is It Bug?

MRAB python at mrabarnett.plus.com
Sat Dec 7 20:12:44 EST 2013


On 08/12/2013 00:59, Mahan Marwat wrote:
> Why this is not working.
>
>>>> 'Hello, \\\\World'.replace('\\', '\\')
>
> To me, Python will interpret '\\\\' to '\\'. And the replace method
> will replace '\\' with '\'. So, the result will be 'Hello, \World'.
> But it's give me 'Hello, \\\\World'.
>
> The result I want form the code is 'Hello, \World'.
>
The original string contains 2 actual backslashes:

>>> print('Hello, \\\\World')
Hello, \\World

Both the search and replacement strings contain 1 backslash:

>>> print('\\')
\

You're asking it to replace every backslash with a backslash!

If you want to replace 2 consecutive backslashed with a single
backslash:

 >>> 'Hello, \\\\World'.replace('\\\\', '\\')
'Hello, \\World'

Maybe it's clearer if you print it:

 >>> print('Hello, \\\\World'.replace('\\\\', '\\'))
Hello, \World



More information about the Python-list mailing list