I have a line that looks like a list, say:
fruits = "['apple', 'orange', 'banana']"
How can I convert this to a list object?
>>> 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.
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.
A simple call to eval() will do:
eval()
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.
I think ast.literal_eval is for this purpose.
( http://docs.python.org/library/ast.html#ast.literal_eval )