12
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']"]
2
  • 2
    Why do you have to do this? Commented Sep 23, 2013 at 19:06
  • 4
    How did you get this string? That will usually tell you how to evaluate it—do the opposite of whatever you did to get the string. To reverse json.dumps, use json.loads, and so on. If you got it by repr, not everything can be reversed, and not everything that can be should be… but ast.literal_eval is the answer for things that can/should. Commented Sep 23, 2013 at 19:12

2 Answers 2

20

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'>
Sign up to request clarification or add additional context in comments.

Comments

0

You can use eval:

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

4 Comments

Please don't use eval! It is unsafe, as it allowes arbitrary code to be executed.
You can, but you shouldn't. As the eval docs explicitly say.
More bluntly: temp = "['a', __import__('os').system('rm -rf /'), 'c']".
I also learn things on this site answering questions. Thanks for the example of why this is dangerous :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.