使用ast.literal_eval
:
>>> import ast
>>> s = "['11', '20', '0']"
>>> lst = ast.literal_eval(s)
>>> lst
['11', '20', '0']
如果要将列表项转换为整数,请使用int()
with或列表推导: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.