[Tutor] Extracting the list from a string

Steven D'Aprano steve at pearwood.info
Wed Jul 11 11:10:19 CEST 2012


On Wed, Jul 11, 2012 at 02:18:04PM +0530, kala Vinay wrote:
> Hi all,
> 
>        say i have a string s="['a','b']" and i want to get a list object
> from this string s ie l=['a','b']

The AST module contains a safe way to parse and eval literal 
expressions, including strings, nested lists, and builtin constants like 
None, True and False.

py> import ast
py> ast.literal_eval('[23, 42, "hello", "world", -1.5, [], {}]')
[23, 42, 'hello', 'world', None, True, False, -1.5, [], {}]

Unlike the eval command, it is safe and won't execute code:

py> text = '__import__("os").system("echo \\"Your computer is mine now!\\"")')
py> eval(text)
Your computer is mine now!
0
py> ast.literal_eval(text)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/ast.py", line 68, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib/python2.6/ast.py", line 67, in _convert
    raise ValueError('malformed string')
ValueError: malformed string


-- 
Steven



More information about the Tutor mailing list