How to turn a string into a list in python?

2020-04-13 12:12发布

l = "['Hello', 'my', 'name', 'is', 'Apple']"
l1 = ['Hello', 'my', 'name', 'is', 'Apple']

type(l) returns str but I want it to be a list, as l1 is.

How can I transform that string into a common list?

2条回答
放我归山
2楼-- · 2020-04-13 12:35

the ast module has a literal_eval that does what you want

import ast
l = "['Hello', 'my', 'name', 'is', 'Apple']"
l1 = ast.literal_eval(l)

Outputs:

['Hello', 'my', 'name', 'is', 'Apple']

docs

查看更多
家丑人穷心不美
3楼-- · 2020-04-13 12:37

ast.literal_eval is a nice approach. For those preferint string manipulation, another option is:

l1 = [x[1:-1] for x in l[1:-1].split(', ')]
查看更多
登录 后发表回答