0

I have a string that already looks like a list:

activeStateString = "['11', '20', '0']"

And I would like to define this as a list in Python. I know that I can start to filter and break it apart and rebuild a new list but then I have to go into loops etc. Is there a way in Python to promote that string from a "string" to a list straight away? So once it is converted:

activeStateString -> activeStateList

I get:

11

for:

print activeStateList[0]

Thanks

(Python 2.6)

mbilyanov
  • 2,315
  • 4
  • 29
  • 49

2 Answers2

7

Use ast.literal_eval() to interpret strings containing Python literals:

>>> import ast
>>> ast.literal_eval("['11', '20', '0']")
['11', '20', '0']

This is safer that using eval() as it will refuse to interpret anything that is not a literal value:

>>> eval("__import__('sys').version")
'2.7.5 (default, Oct 28 2013, 20:45:48) \n[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)]'
>>> ast.literal_eval("__import__('sys').version")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/ast.py", line 80, in literal_eval
    return _convert(node_or_string)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

Use ast.literal_eval:

>>> import ast
>>> s = "['11', '20', '0']"
>>> lst = ast.literal_eval(s)
>>> lst
['11', '20', '0']

Use int() with map or a list comprehension if you want to convert the list items to integers:

>>> map(int, lst)
[11, 20, 0]

Help on 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, numbers, tuples, lists, dicts, booleans,
    and None.
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504