Is It Bug?

Peter Otten __peter__ at web.de
Sun Dec 8 11:43:37 CET 2013


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'.

Let's forget about backslashes for the moment and use 'a' instead. We can 
replace an 'a' with an 'a'

>>> "Hello, aaWorld".replace("a", "a")
'Hello, aaWorld'

That changes nothing. Or we can replace two 'a's with one 'a'

>>> "Hello, aaWorld".replace("aa", "a")
'Hello, aWorld'

This does the obvious thing. Finally we can replace an 'a' with the empty 
string '':

>>> "Hello, aaWorld".replace("a", "")
'Hello, World'

This effectively removes all 'a's. 

Now let's replace the "a" with a backslash. Because the backslash has a 
special meaning it has to be "escaped", i. e. preceded by another backslash. 
The examples then become

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

While doubling of backslashes is required by Python the doubling of 
backslahses in the output occurs because the interactive interpreter applies 
repr() to the string before it is shown. You can avoid that with an explicit 
print statement in Python 2 or a print() function call in Python 3:

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




More information about the Python-list mailing list