Python将字符串列表转换为python列表

拉胡尔

我有来自数据库的字符串形式的数据。

例如 = ['foo1', 'bar1', 'foo2', 'bar2'] 并且类型是类 'str'

我想将其转换为 python 列表。

>>> db_string = ['foo1', 'bar1', 'foo2', 'bar2']
>>> db_string.strip('][').split(', ')
["'foo1'", "'bar1'", "'foo2'", "'bar2'"]

我想要更好的解决方案。

路跑者

使用ast.literal_eval

>>> from ast import literal_eval
>>> db_string = "['foo1', 'bar1', 'foo2', 'bar2']"
>>> result = literal_eval(db_string)
>>> result
['foo1', 'bar1', 'foo2', 'bar2']
>>> type(result)
<class 'list'>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将列表列表转换为字符串列表

将字符串列表转换为python中的元组列表

将列表转换为字符串列表python

Python将未知长度的(字符串)元组转换为字符串列表

Python将字符串列表转换为列表

使用Python3.5的Cython:将字符串列表转换为char **

将字符串列表转换为python中的列表

如何在Python3中将字符串列表转换为整数?

在Python中将列表的字符串列表转换为整数

将多个字符串列表转换为Python数据框

Python将字符串列表转换为整数列表

Python:将字符串列表转换为带有空/无的浮点数

将列表(对象)列表转换为字符串列表

Python-将长地址列表转换为字符串列表和列表的交集

Python将字符串列表转换为元组列表

将unicode列表转换为python中的字符串列表

如果可能,将字符串列表转换为float。- Python

Python 2.7将字符串列表转换为字典

Python将字符串列表转换为Unicode

将字符串列表转换为 Numpy 数组 (Python)

将字符串列表转换为 Python 中的纯列表

字符串列表转换为浮点python

将字符串列表转换为指定格式的原始python列表

如何将 Python 字符串列表转换为 wchar_t 的 C 数组?

python将字符串列表转换为CSV

使用 Python 将字符串列表转换为 URL 列表

将字符串列表中的数字转换为 Python 中的 int

将列中的字符串列表转换为分隔列 Python

PYthon - 将字符串列表转换为嵌套的字符串列表,其中每个列表包含每个字符串的元素