Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string representation of a list into an actual list object [duplicate]

I have a string that looks identical to a list, let's say:

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

What would be the way to convert that to a list object?

like image 549
Markum Avatar asked May 27 '12 17:05

Markum


People also ask

Can you convert a string to a list?

Strings can be converted to lists using list() .

How do I convert a string to a list that looks like a list in Python?

How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.


3 Answers

>>> fruits = "['apple', 'orange', 'banana']" >>> import ast >>> fruits = ast.literal_eval(fruits) >>> fruits ['apple', 'orange', 'banana'] >>> fruits[1] 'orange' 

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

Safely evaluate an expression node or a 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.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

like image 106
fraxel Avatar answered Sep 22 '22 12:09

fraxel


A simple call to eval() will do:

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

Or as explained in this article, the same can be accomplished a bit more safely (meaning: without risking unintended side-effects or malicious code injections) like this:

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

This solution has the advantage of not depending on additional modules.

like image 45
Óscar López Avatar answered Sep 22 '22 12:09

Óscar López


I think this is what ast.literal_eval is for.

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

like image 28
mgilson Avatar answered Sep 21 '22 12:09

mgilson