Python下如何将字符串类型的列表转换为列表对象?

有个程序,接受外面传值,对方传过来的是字符串列表:

"['/data/app/web/conf/aa.conf', '/data/app/web/conf/bb.conf', '/data/app/web/conf/cc.conf']"

然后我使用list(data),返回结果是:

['[', "'", '/', 'd', 'a', 't', 'a', '/', 'a', 'p', 'p', '/', 'w', 'e', 'b', '/', 'c', 'o', 'n', 'f', '/', 'a', 'a', '.', 'c', 'o', 'n', 'f', "'", ',', ' ', "'", '/', 'd', 'a', 't', 'a', '/', 'a', 'p', 'p', '/', 'w', 'e', 'b', '/', 'c', 'o', 'n', 'f', '/', 'b', 'b', '.', 'c', 'o', 'n', 'f', "'", ',', ' ', "'", '/', 'd', 'a', 't', 'a', '/', 'a', 'p', 'p', '/', 'w', 'e', 'b', '/', 'c', 'o', 'n', 'f', '/', 'c', 'c', '.', 'c', 'o', 'n', 'f', "'", ']']

Python下有其他好的办法吗,这不是我想要的结果,我想要的是可以直接类型转换,然后使用吗?

已邀请:

OS小编 - 开源技术社区小编,我就是这么爱学习!

当然有了,Python下可以利用ast模块解决这个问题,示例如下:

from ast import literal_eval

str_tuple = "(1, 2, 3, 4)"
str_list = "[1, 2, 3, 4]"
str_set = "{1, 2, 3, 4}"
str_dict = "{'name': 'lucky', 'age': 18, 'job': 'Dev'}"

tuple_info = literal_eval(str_tuple)
list_info = literal_eval(str_list)
set_info = literal_eval(str_set)
dict_info = literal_eval(str_dict)
print(' tuple_info type: %s\n list_info type: %s\n set_info type: %s\n dict_info type %s' %
(type(tuple_info), type(list_info), type(set_info), type(dict_info))
)

结果如下:

tuple_info type: <class 'tuple'>
list_info type: <class 'list'>
set_info type: <class 'set'>
dict_info type <class 'dict'>

如上可知,基本元组、列表、集合、字典,都可以转换,  参考:Preferred over eval 。

要回复问题请先登录注册