2011-05-13 603 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