Search code examples
pythonstring

Escape double quotes for JSON in Python


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'

Solution

  • >>> 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
    >>>