Replace character with backslash error - Python

This seems like a mistake. I cannot replace a character in a string with one backslash:

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

I know that '\' not a legal string because \ escapes the latter ' . However, I do not want the result to be 'a\\b' ; I want it to be 'a\b' . How is this possible?

+4
source share
1 answer

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

\\ itself is just one slash, but is displayed as an escaped character to make the value a valid Python literal string. You can copy and paste this line back into Python and this will give the same value.

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

 >>> st = "a&b" >>> print st.replace('&','\\') a\b >>> len(st.replace('&','\\')) 3 
+11
source

Source: https://habr.com/ru/post/1488109/


All Articles