Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a character with backslash bug - Python

This feels like a bug to me. I am unable to replace a character in a string with a single backslash:

>>>st = "a&b"
>>>st.replace('&','\\')
'a\\b'

I know that '\' isn't a legitimate string because the \ escapes the last '. However, I don't want the result to be 'a\\b'; I want it to be 'a\b'. How is this possible?

like image 836
Jordan Avatar asked Jun 25 '13 15:06

Jordan


1 Answers

You are looking at the string representation, which is itself a valid Python string literal.

The \\ is itself just one slash, but displayed as an escaped character to make the value a valid Python literal string. You can copy and paste that string back into Python and it'll produce the same value.

Use print st.replace('&','\\') to see the actual value being displayed, or test for the length of the resulting value:

>>> st = "a&b"
>>> print st.replace('&','\\')
a\b
>>> len(st.replace('&','\\'))
3
like image 190
Martijn Pieters Avatar answered Oct 11 '22 19:10

Martijn Pieters