简体   繁体   English

将字符串转换为列表。 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 我知道一种方法,但我宁愿不使用正则表达式

if i use temp.split() I get 如果我使用temp.split()我得到

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

Use ast.literal_eval() : 使用ast.literal_eval()

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. 安全地评估表达式节点或包含Python表达式的Unicode或Latin-1编码的字符串。 The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. 提供的字符串或节点可能只包含以下Python文字结构:字符串,数字,元组,列表,dicts,布尔值和None。

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

You can use eval : 你可以使用eval

>>> temp = "['a', 'b', 'c']"
>>> temp_list = eval(temp)
>>> temp_list
['a', 'b', 'c']
>>> temp_list[1]
b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM