How can I replace double quotes with a backslash and double quotes in Python?
如何在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'
4 个解决方案
#1
13
>>> 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'它就会逃脱\为你,当你打印它时,你会看到字符串更“原始”状态。所以现在......
>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
>>> print s.replace('"', '\\"')
my string with \"double quotes\" blablabla
>>>
#2
71
You should be using the json
module. json.dumps(string)
. It can also serialize other python data types.
你应该使用json模块。 json.dumps(字符串)。它还可以序列化其他python数据类型。
import json
>>> s = 'my string with "double quotes" blablabla'
>>> json.dumps(s)
<<< '"my string with \\"double quotes\\" blablabla"'
#3
19
Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:
请注意,您可以通过执行两次json.dumps和两次json.loads来转义json数组/字典:
>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}
#4
-3
Why not do string suppression with triple quotes:
为什么不使用三引号进行字符串抑制:
>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes
#1
13
>>> 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'它就会逃脱\为你,当你打印它时,你会看到字符串更“原始”状态。所以现在......
>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
>>> print s.replace('"', '\\"')
my string with \"double quotes\" blablabla
>>>
#2
71
You should be using the json
module. json.dumps(string)
. It can also serialize other python data types.
你应该使用json模块。 json.dumps(字符串)。它还可以序列化其他python数据类型。
import json
>>> s = 'my string with "double quotes" blablabla'
>>> json.dumps(s)
<<< '"my string with \\"double quotes\\" blablabla"'
#3
19
Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:
请注意,您可以通过执行两次json.dumps和两次json.loads来转义json数组/字典:
>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}
#4
-3
Why not do string suppression with triple quotes:
为什么不使用三引号进行字符串抑制:
>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes