Python - escaping double quotes using string.replace
How to replace "using" with python string?
I have a double quote string:
s = 'a string with "double" quotes' I want to avoid double quotes with one backslash.
Doing the following doesn't quite work; it disappears with two backslashes:
s.replace('"', '\\"') 'a string with \\"double\\" quotes' Printing the output of this line shows what I want. But I do not just want to print the correct line, I want it to be stored in a variable. Can someone help me with the correct magical regex?
The string is correct. But repr will use backslash screens to display non-printable characters and for consistency (it should form a Python string literal, which when calculating returns the same string as the input to repr ), also speeds up every backslash that occurs in a string.
Please note that this is a fairly limited shielding algorithm. Depending on what you need it for, you may have to significantly expand it (or there is a ready-made solution, for example, prefix statements when working with databases)
Your original attempt works fine. You see a double backslash - it's just a way of displaying single backslashes that are actually in a string. See Also: __repr__()
>>> s = 'a string with "double" quotes' >>> ss = s.replace('"', '\\"') >>> len(s) 29 >>> len(ss) 31 one backslash is not visible, but the backslash remains on the line. if you check the length of the same line, you can see the answer. Also, if you replace the newline again with double quotes, you will get the original string.