python - 将字符串转换为列表。 Python [string.split() 行为怪异]

标签 python string list split

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

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

所以我有这个临时字符串,它基本上是一个字符串格式的列表。 . .我正试图将它重新变成一个列表,但我不确定这样做的简单方法。我知道一种方法,但我宁愿不使用正则表达式

如果我使用 temp.split() 我得到

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

最佳答案

使用ast.literal_eval() :

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

>>> from ast import literal_eval
>>> temp = "['a','b','c']"
>>> l = literal_eval(temp)
>>> l
['a', 'b', 'c']
>>> type(l)
<type 'list'>

关于python - 将字符串转换为列表。 Python [string.split() 行为怪异],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18966798/

相关文章:

python - 从最后一个产生的对象而不是值中查找元素

python - 添加一个小部件(QProgressbar)作为 QTreeView 中的子项

javascript - 我可以在 Javascript 或 JSX 中将解包对象作为参数传递吗?

python - 全日历和 django

PHP 的 stripslashes 的 Python 版本

Python 比较列表中的部分字符串

python - 订购 list

python - 为什么初始化列表列表的代码显然将列表链接在一起?

python - 使用Python测量音频输出电平?

c++ - 为什么函数返回一个空字符串