How do I replace " with \" in a python string?
I have a string with double quotes:
s = 'a string with "double" quotes'
I want to escape the double quotes with one backslash.
Doing the following doesn't quite work, it escapes with two backslashes:
s.replace('"', '\\"')
'a string with \\"double\\" quotes'
Printing the output of that string shows what I want. But I don't just want to print the correct string, I want it saved in a variable. Can anyone help me with the correct magical regular expression?
Your original attempt works just fine. The double backslashes you see are simply a way of displaying the single backslashes that are actually in the string. See also: __repr__()
>>> s = 'a string with "double" quotes'
>>> ss = s.replace('"', '\\"')
>>> len(s)
29
>>> len(ss)
31
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With