I have a list formatted as shown here:
>>> x = "[26, 25]"
>>> list(x)
['[', '2', '6', ',', ' ', '2', '5', ']']
How do I convert to a list with elements as shown here:
>>> x
[25, 26]
Use ast.literal_eval():
import ast
ast.literal_eval(x)
or treat it as JSON, using json.loads():
import json
json.loads(x)
ast.literal_eval() takes Python literals as input (so text that in Python source code would give you a value), json.loads() takes JSON input.
Demo:
>>> import ast, json
>>> x = "[26, 25]"
>>> ast.literal_eval(x)
[26, 25]
>>> json.loads(x)
[26, 25]
The difference between the two only comes into play when you have more than a list of integers in your input string; JSON strings contain unicode, which ast.literal_eval() on Python 2 would not interpret correctly, and JSON types are only a subset of what ast.literal_eval() supports.
>>> x = '["List", "with", "strings", "including", "snowman", "\u2603"]'
>>> ast.literal_eval(x)
['List', 'with', 'strings', 'including', 'snowman', '\\u2603']
>>> json.loads(x)
[u'List', u'with', u'strings', u'including', u'snowman', u'\u2603']
>>> x = "(1, 2, 3, 'a tuple is Python syntax, not JSON')"
>>> ast.literal_eval(x)
(1, 2, 3, 'a tuple is Python syntax, not JSON')
>>> json.loads(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/decoder.py", line 383, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded