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 \"