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 chunk of code it represents, and to do this there are some options.
Ast.literal_eval()
Whereas the string contains Python code and is a literal structure (string
, number
, tuple
, list
, dict
, boolean
or None
), you can use the function ast.literal_eval()
. The library ast
enables the programmatic interpretation of the 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
(exemlo no repl.it: https://repl.it/M4fP/1)
json.loads()
Since your string example for parse also represents a JSON array, you can use the Python JSON parser to interpret it safely, as shown by @Anderson-carlos-woss in the accepted answer:
>>> import json
>>> retorno = '[[10, 20], 10]'
>>> a = json.loads(retorno)
>>> print(a[0][0])
10
>>> print(a[0][1])
20
(example in repl.it: https://repl.it/M4fP/2)
yaml.safe_load
Parsers from other serialization languages that use array representation equal to JSON, such as YAML (actually JSON is a "subgroup" of YAML), may also be useful to you. YAML particularly has a function safe_load()
:
>>> import yaml
>>> retorno = '[[10, 20], 10]'
>>> a = yaml.safe_load(retorno)
>>> print(a[0][0])
10
>>> print(a[0][1])
20
(example in repl.it: https://repl.it/M4fP/3)
More about YAML parser and secure data entry in Python programs: Openstack: Avoid Dangerous file Parsing and Object serialization Libraries
Eval() (high security risk)
The option less secure is the use of the function eval()
. It takes a Python code string and executes it:
>>> retorno = '[[10, 20], 10]'
>>> a = eval(retorno)
>>> print(a[0][0])
10
>>> print(a[0][1])
20
(example in repl.it: https://repl.it/M4fP/0)
The lack of security is due to the fact that the function eval()
execute each and every code past. Therefore, the results can be catastrophic if some malicious user is able to change their database data to that variable retorno
contain any unwanted commands. As a rule, do not use eval()
even if you trust the string, because you never know how it can be intercepted by someone.
For more information about the danger of using eval()
:
Stack Overflow: Eval is either a bad guy or a bad guy?
Ned Batchelder: Eval really is Dangerous
Kevin London: Dangerous Python Functions, Part 1
But what you’re getting from the bank is a string, not a list. The object
a
is a list with only one value, of the type string.– Woss
Yes. You’re right! There is some way to fix this. I ask, why don’t I really know @Andersoncarloswoss.
– Danilo
Danilo, what do these values represent? Why are they stored like this in the table?
– Woss