Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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?"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading