Python @ DjangoSpin

PyPro #61 Converting a string-containing-list-syntax to a list

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Converting a string-containing-list-syntax to a list in Python

Converting a string-containing-list-syntax to a list in Python

Converting a string-containing-list-syntax to a list. Given a list stored as a string, write a Python program to extract the list.

Converting a string-containing-list-syntax to a list

import ast

trees = "['Oak', 'Eucalyptus', 'Banyan', 'Amla']"  

print(ast.literal_eval(trees))  			# ['Oak', 'Eucalyptus', 'Banyan', 'Amla']

Here's the help text associated with ast.literal_eval().

>>> help(ast.literal_eval)
Help on function literal_eval in module ast:

literal_eval(node_or_string)
    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, bytes, numbers, tuples, lists, dicts,
    sets, booleans, and None.

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply