Python - escaping double quotes using string.replace

Viewed 48797

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?

5 Answers

The other answers can be dangerous and fail


For example:

  • The literal string Hello \" (e.g. print('Hello \\"'))
    would become Hello \\" 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 \"
Related