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 variabl开发者_如何学JAVAe. 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
The string is correct. But repr
will use backslash-escapes itself to show unprintable characters, and for consistency (it's supposed to form a Python string literal that, when evaluated, gives back the same string that was the input to repr
) also escapes each backslash that occurs in the string.
Note that this is a rather limited escaping algorithm. Depending on what you need it for, you may have to expand it significantly (or there's a ready-made solution, e.g. preprared statements when working with databases)
This did the job for me.
s.replace('"', '\\"')
The other answers can be dangerous and fail
For example:
- The literal string
Hello \"
(e.g.print('Hello \\"')
)
would becomeHello \\"
which does not escape the"
!
it escapes the\
instead! - Even if that edgecase is added, things like
Hello \\\\\"
would likely cause problems - This is how injection attacks happen (manually escaping strings is generally an error-prone job)
Here is a better solution
def escape_double_quotes(string):
return string.replace('\\','\\\\').replace('"',r'\"')
print(escape_double_quotes('Howdy \"')) # Howdy \"
print(escape_double_quotes('Howdy \\"')) # Howdy \\\"
BUT
This doesn't escape everything. It should only ensure that double-quotes are always escaped.
To escape everything for python, try using json.dumps
. But again, note "escaping" depends on who is reading. This method would NOT be safe for database queries or dumping into web pages.
import json
def escape_double_quotes(string):
return json.dumps(string)[1:-1]
print(escape_double_quotes('Howdy \"'))) # Howdy \"
print(escape_double_quotes('Howdy \\"')) # Howdy \\\"
print(escape_double_quotes('Howdy \n \"')) # Howdy \n \"
one backslash cannot be seen, but the backslash remains in the string. if you will check the length of same string you will able to see answer. Also, if you will replace new string again with double quotes, you will get original string.
精彩评论