python's string replace method replaces backslashes

When replacing a substring from a string, I expect the backslash (\) to stay untouched.

test1 = "This is a \ test String?"
test1.replace("?", "!")
'This is a \\ test String!'

test2 = "This is a '\' test String?"
test2.replace("?", "!")
"This is a '' test String!"

What I expect is "This is a \ test String!" or "This is a '\' test String!" respectively. How can I achieve that?

>Solution :

Two issues.

First case, you’re getting the representation not the string value. that’s a classic explained for instance here: Python prints two backslash instead of one

Second case, you’re escaping the quote unwillingly. Use raw string prefix in all cases (specially treacherous with Windows hardcoded paths where \test becomes <TAB>est):

test2 = r"This is a '\' test String?"

In the first case, it "works" because \ doesn’t escape anything (for a complete list of escape sequences, check here), but I would not count too much on that in the general case. That raw prefix doesn’t hurt either:

test1 = r"This is a \ test String?"

Leave a Reply