将字符串转换为列表. Python [string.split()表现怪异] [英] Convert string to list. Python [string.split() acting weird]
问题描述
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
如果我使用temp.split()我会得到
if i use temp.split() I get
temp_2 = ["['a','b','c']"]
推荐答案
使用 ast.literal_eval()
:
安全地评估表达式节点或Unicode或Latin-1编码 包含Python表达式的字符串.提供的字符串或节点可以 仅包含以下Python文字结构:字符串, 数字,元组,列表,字典,布尔值和无.
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 [string.split()表现怪异]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!