Jordan
Jordan

Reputation: 181

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?

Upvotes: 8

Views: 2013

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121416

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

Upvotes: 15

Related Questions