如何在python中将数组字符串转换为数组

时间:2014-08-29 16:20:13

标签: python mysql arrays

我试图将存储在mysql数据库中的数组(作为字符串)转换为python中的标准数组,这就是我的意思:

这是我从数据库中得到的:

"['a',['b','c','d'],'e']" # this is a string in the format of an array that holds strings inside it.

我需要从字符串中删除数组,使其像普通数组一样运行 任何帮助将不胜感激。我不确定这是否已在其他地方得到解答,抱歉,如果有,我找不到它。 感谢

2 个答案:

答案 0 :(得分:7)

您可以使用ast.literal_eval

>>> from ast import literal_eval
>>> s = "['a',['b','c','d'],'e']"
>>> print(literal_eval(s))
['a', ['b', 'c', 'd'], 'e']

答案 1 :(得分:0)

如果您可以将这些单引号转换为双引号,则可以使用json解析。

import json
obj1 = json.loads('["a", ["b", "c", "d"], "e"]')