我有一个看起来像列表的字符串:
activeStateString = "['11', '20', '0']"
我想将其定义为Python中的列表。我知道我可以开始过滤并拆分它并重建一个新列表但是我必须进入循环等。在Python中是否有办法将字符串从“字符串”直接提升到列表?所以一旦转换:
activeStateString -> activeStateList
我明白了:
11
有:
print activeStateList[0]
由于
(Python 2.6)
答案 0 :(得分:5)
使用ast.literal_eval()
来解释包含Python文字的字符串:
>>> import ast
>>> ast.literal_eval("['11', '20', '0']")
['11', '20', '0']
使用eval()
更安全,因为它会拒绝解释任何不字面值的内容:
>>> eval("__import__('sys').version")
'2.7.5 (default, Oct 28 2013, 20:45:48) \n[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)]'
>>> ast.literal_eval("__import__('sys').version")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
答案 1 :(得分:2)
>>> import ast
>>> s = "['11', '20', '0']"
>>> lst = ast.literal_eval(s)
>>> lst
['11', '20', '0']
如果要将列表项转换为整数,请将int()
与map
或列表推导使用:
>>> map(int, lst)
[11, 20, 0]
ast.literal_eval
的帮助:
>>> help(ast.literal_eval)
Help on function literal_eval in module ast:
literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.