12
temp = "['a','b','c']"
print type(temp)
#string

output = ['a','b','c']
print type(output)
#list

so i have this temporary string which is basically a list in string format . . . i'm trying to turn it back into a list but i'm not sure a simple way to do it . i know one way but i'd rather not use regex

if i use temp.split() I get

temp_2 = ["['a','b','c']"]
4

2 回答 2

20

使用ast.literal_eval()

安全地评估包含 Python 表达式的表达式节点或 Unicode 或 Latin-1 编码字符串。提供的字符串或节点只能由以下 Python 文字结构组成:字符串、数字、元组、列表、字典、布尔值和无。

>>> from ast import literal_eval
>>> temp = "['a','b','c']"
>>> l = literal_eval(temp)
>>> l
['a', 'b', 'c']
>>> type(l)
<type 'list'>
于 2013-09-23T19:02:31.760 回答
0

您可以使用eval

>>> temp = "['a', 'b', 'c']"
>>> temp_list = eval(temp)
>>> temp_list
['a', 'b', 'c']
>>> temp_list[1]
b
于 2013-09-23T19:11:51.287 回答