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']"]
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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) <type 'list'>
Method 2
You can use eval:
>>> temp = "['a', 'b', 'c']" >>> temp_list = eval(temp) >>> temp_list ['a', 'b', 'c'] >>> temp_list[1] b
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0