58

How can I replace double quotes with a backslash and double quotes in Python?

>>> s = 'my string with "double quotes" blablabla'
>>> s.replace('"', '\\"')
'my string with \\"double quotes\\" blablabla'
>>> s.replace('"', '\\\"')
'my string with \\"double quotes\\" blablabla'

I would like to get the following:

'my string with \"double quotes\" blablabla'
phwd
  • 19,969
  • 5
  • 49
  • 78
aschmid00
  • 6,938
  • 2
  • 45
  • 66

4 Answers4

128

You should be using the json module. json.dumps(string). It can also serialize other python data types.

import json

>>> s = 'my string with "double quotes" blablabla'

>>> json.dumps(s)
<<< '"my string with \\"double quotes\\" blablabla"'
zeekay
  • 49,858
  • 13
  • 107
  • 105
  • 2
    Why does json.dumps() add in all of the extra quotes? Why does it add an extra backslash i.e., \\", instead of just \" ? – user798719 Jul 04 '13 at 01:39
  • 8
    @user798719 it doesnt add extra \. thats the way it prints it in console. – Victor Miroshnikov Aug 01 '13 at 18:07
  • TIL json.dumps can act on singleton strings as well as `dict` objects. – MarkHu Apr 22 '14 at 23:30
  • 1
    Would like to state that even though this is a nice method since it uses a standard library and has simple usage, using `json.dumps` is slow. Where speed is a crucial element, I would not recommend using this method. – Ashish Ahuja Aug 17 '18 at 08:53
49

Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:

>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}
Medhat Gayed
  • 2,267
  • 18
  • 11
24
>>> s = 'my string with \\"double quotes\\" blablabla'
>>> s
'my string with \\"double quotes\\" blablabla'
>>> print s
my string with \"double quotes\" blablabla
>>> 

When you just ask for 's' it escapes the \ for you, when you print it, you see the string a more 'raw' state. So now...

>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
>>> print s.replace('"', '\\"')
my string with \"double quotes\" blablabla
>>> 
Andrew
  • 2,494
  • 16
  • 9
0

i know this question is old, but hopefully it will help someone. i found a great plugin for those who are using PyCharm IDE: string-manipulation that can easily escape double quotes (and many more...), this plugin is great for cases where you know what the string going to be. for other cases, using json.dumps(string) will be the recommended solution

str_to_escape = 'my string with "double quotes" blablabla'

after_escape = 'my string with \"double quotes\" blablabla'
Tam Nguyen
  • 58
  • 7