Convert string to list. Python [string.split() acting weird]

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

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_2 = ["['a','b','c']"] 

回答1:

Use 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) 


回答2:

You can use eval:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!