Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - escaping double quotes using string.replace

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?

like image 708
Stephen Avatar asked Jun 23 '11 19:06

Stephen


1 Answers

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
like image 127
ʇsәɹoɈ Avatar answered Oct 06 '22 01:10

ʇsәɹoɈ