将str转换为python中的列表

时间:2018-02-23 17:23:22

标签: python python-2.7

我有一个像这样的python str对象,我想将其转换为列表

l = "['Incorrect password.$', 'Login failed']"  --- type <str>

预期产出

l = ['Incorrect password.$', 'Login failed']  ---- type <list>

试验1:

p = list(l)

它将l设为['[', "'", 'I', 'n', 'c', 'o', 'r', 'r', 'e', 'c', 't', ' ', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd', '.', '$', "'", ',', ' ', "'", 'L', 'o', 'g', 'i', 'n', ' ', 'f', 'a', 'i', 'l', 'e', 'd', "'", ']']

试验2:

  l.split(',')

第二种方法不合适,因为列表元素本身可能包含逗号。

我该怎么办? 任何提示都表示赞赏。

2 个答案:

答案 0 :(得分:5)

使用 ast 模块

import ast
l = "['Incorrect password.$', 'Login failed']"
print l, type(l)
l =  ast.literal_eval(l)
print l, type(l)

<强>输出:

['Incorrect password.$', 'Login failed'] <type 'str'>
['Incorrect password.$', 'Login failed'] <type 'list'>

答案 1 :(得分:1)

eval(l)

eval()是一个内置函数,用于评估代码。