2011-05-13 49 views
23

如何用Python中的反斜杠和双引号替换双引号?在Python中为JSON换掉双引号

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

我想获得如下:

'my string with \"double quotes\" blablabla' 

回答

11
>>> s = 'my string with \\"double quotes\\" blablabla' 
>>> s 
'my string with \\"double quotes\\" blablabla' 
>>> print s 
my string with \"double quotes\" blablabla 
>>> 

当你刚刚问的'它为了你,当你打印它时,你会看到字符串更“原始”的状态。所以现在...

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

这是'repr()'和'str()'之间的区别。 'print s'打印字符串,而命令行中的's'与'print repr(s)'做同样的事情。 – 2011-05-13 20:00:28

+1

-1,因为下面的@zeekay提供了一个更理想的答案:'json.dumps(s)'。它使用标准的JSON库来达到预期的效果。当你遇到这个代码时,你马上会看到我们正在处理JSON序列化。 OTOH,当你看到s.replace(''','\\''')'时,你必须猜测发生了什么。 – 2011-05-15 16:53:59

+1

有时嵌入式python可能无法访问所有导入。 – AnthonyVO 2012-04-11 15:47:25

-2

为什么不串抑制三重引号:

>>> s = """my string with "some" double quotes""" 
>>> print s 
my string with "some" double quotes 
+0

,因为我需要这个字符串JSON。我需要\在那里。 – aschmid00 2011-05-13 19:53:48

+0

我想他想保留\以便在json中引号将被转义。 – Andrew 2011-05-13 19:56:32

65

您应该使用json模块。 json.dumps(string)。它也可以序列化其他Python数据类型。

import json 

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

>>> json.dumps(s) 
<<< '"my string with \\"double quotes\\" blablabla"' 
+1

尼斯和思维敏捷:)删除我多余的答案。 – 2011-05-13 20:07:26

+0

为什么json.dumps()会添加所有额外的引号?为什么会添加一个额外的反斜杠,即\\“,而不是”\“? – user798719 2013-07-04 01:39:35

+2

@ user798719它不会添加额外的\。这就是它在控制台中打印它的方式。 – 2013-08-01 18:07:50

15

需要注意的是,你可以通过做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} 
+0

Python FTW !!! :( – 2017-12-31 15:20:16