The return you get from the database is a string that represents the syntax of a Python list, not a list itself. To use it as a list, you need Python to interpret the snippet of code it represents, and to do that there are a few options.
ast.literal_eval ()
Considering that the string contains Python code and it is a literal structure ( string
, number
, tuple
, list
, dict
, boolean
, or None
), you can use the ast.literal_eval()
function. The ast
library enables the programmatic interpretation of Python syntax, so that the function in question receives a literal structure string and returns it interpreted at runtime:
>>> import ast
>>> retorno = '[[10, 20], 10]'
>>> a = ast.literal_eval(retorno)
>>> print(a[0][0])
10
>>> print(a[0][1])
20
(example in repl.it: link )
json.loads ()
Since your parse string example also represents a JSON array, you can use the JSON parser Python to interpret it safely, as shown by @ anderson-carlos-woss in the accepted response:
>>> import json
>>> retorno = '[[10, 20], 10]'
>>> a = json.loads(retorno)
>>> print(a[0][0])
10
>>> print(a[0][1])
20
(example in repl.it: link )
yaml.safe_load
Parsers of other serialization languages that use JSON arrays, such as the YAML (
12.10.2017 / 01:18