Converting a string representation of a list to an actual list object

I have a line that looks like a list, say:

fruits = "['apple', 'orange', 'banana']" 

How can I convert this to a list object?

+52
python string list
May 27 '12 at 17:26
source share
3 answers
 >>> fruits = "['apple', 'orange', 'banana']" >>> import ast >>> fruits = ast.literal_eval(fruits) >>> fruits ['apple', 'orange', 'banana'] >>> fruits[1] 'orange' 

As stated in the comments ast.literal_eval is safe . From the docs:

It is safe to evaluate a node expression or a string containing a Python expression. The string or node provided can only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used to safely evaluate strings containing Python expressions from untrusted sources without the need to parse valued ones.

+69
May 27 '12 at 17:28
source share

A simple call to eval() will do:

 fruits = eval("['apple', 'orange', 'banana']") fruits > ['apple', 'orange', 'banana'] 

Or, as described in the article, the same can be done more safely (this means: without the risk of unintended side effects or malicious injection code) as follows:

 fruits = eval("['apple', 'orange', 'banana']", {'__builtins__':None}, {}) 

This solution has the advantage that it does not depend on additional modules.

+15
May 27 '12 at 17:31
source share

I think ast.literal_eval is for this purpose.

( http://docs.python.org/library/ast.html#ast.literal_eval )

+2
May 27 '12 at 17:27
source share



All Articles