8

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?

1 Answer 1

15

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.