我這裏顯示格式化爲一個列表:轉換Python字符串列出
>>> x = "[26, 25]"
>>> list(x)
['[', '2', '6', ',', ' ', '2', '5', ']']
如何轉換與元素的列表如下所示:
>>> x
[25, 26]
我這裏顯示格式化爲一個列表:轉換Python字符串列出
>>> x = "[26, 25]"
>>> list(x)
['[', '2', '6', ',', ' ', '2', '5', ']']
如何轉換與元素的列表如下所示:
>>> x
[25, 26]
import ast
ast.literal_eval(x)
或將其視爲JSON,使用json.loads()
:
import json
json.loads(x)
ast.literal_eval()
以Python文字作爲輸入(因此Python源代碼中的文本會給你一個值),json.loads()
需要JSON輸入。
演示:
>>> import ast, json
>>> x = "[26, 25]"
>>> ast.literal_eval(x)
[26, 25]
>>> json.loads(x)
[26, 25]
兩者之間的區別僅進場時,你有比你輸入字符串整數列表以上; JSON字符串包含unicode,Python 2上的ast.literal_eval()
不能正確解釋,而JSON類型只是ast.literal_eval()
支持的子集。
>>> x = '["List", "with", "strings", "including", "snowman", "\u2603"]'
>>> ast.literal_eval(x)
['List', 'with', 'strings', 'including', 'snowman', '\\u2603']
>>> json.loads(x)
[u'List', u'with', u'strings', u'including', u'snowman', u'\u2603']
>>> x = "(1, 2, 3, 'a tuple is Python syntax, not JSON')"
>>> ast.literal_eval(x)
(1, 2, 3, 'a tuple is Python syntax, not JSON')
>>> json.loads(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/decoder.py", line 383, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
比「EVAL」更好的(從安全和速度(可能)的觀點)將是:
[int(v) for v in x[1:-1].replace(" ", "").split(",")]
另一種選擇,如果你知道自己在做正確的事
x = "[26, 25]"
y = eval(x)
print y
這種方法存在惡意代碼注入的危險 - 如果從文件中讀取x並且黑客以某種方式能夠更改文件... – drevicko
這是證明比使用[安全評估](http://docs.python.org/2/library/ast.html#ast.literal_eval) –
更快你必須'map()'到'int()'以及得到整數。 –
@MartijnPieters謝謝,編輯。 – IProblemFactory