list_example = "['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']"
我想将上面的内容转换为:
list_example = ['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']
我尝试了以下操作:list_example = list_example.split(',')
导致:
["['0101612-0'",
" '0101611-2'",
" '0101610-4'",
" '0101608-8'",
" '0101607-0'",
" '0101606-2'",
" '0100786-3'",
" '0100784-8'",
" '0100783-0'",
" '0100782-2'",
" '0100781-4'",
" '0100780-6'",
" '0100779-8'",
" '0100778-0'",
" '0100777-2']"]
从中提取值是很麻烦的。
答案 0 :(得分:2)
您可以使用ast.literal_eval
:
>>> import ast
>>> s = "['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']"
>>> ast.literal_eval(s)
['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']
您可以使用split
& strip
也是如此,但它有点复杂:
>>> [x.strip('\'') for x in s.strip('[]').split(', ')]
['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']
答案 1 :(得分:-1)
最简单(也可能是最危险)的方法是使用eval
。
my_list = eval(list_example)
此代码应返回一个充满字符串的列表对象。警告:确保用户无法在list_example
内输入任何恶意代码!