将str转换为python中的列表

Gur*_*uru 0 python python-2.7

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

l = "['Incorrect password.$', 'Login failed']"  --- type <str>
Run Code Online (Sandbox Code Playgroud)

预期产出

l = ['Incorrect password.$', 'Login failed']  ---- type <list>
Run Code Online (Sandbox Code Playgroud)

试验1:

p = list(l)
Run Code Online (Sandbox Code Playgroud)

这让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(',')
Run Code Online (Sandbox Code Playgroud)

第二种方法是不利的,因为列表元素本身可能包含逗号.

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

Rak*_*esh 5

使用ast模块

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

输出:

['Incorrect password.$', 'Login failed'] <type 'str'>
['Incorrect password.$', 'Login failed'] <type 'list'>
Run Code Online (Sandbox Code Playgroud)