e.g.:
from :
"[1,2,3]"
to [1,2,3]
as the function int()
makes a "5"
a 5
The json
and ast
packages can help with parsing like this. In this case try:
import json
foo = json.loads("[1,2,3]")
or
import ast
foo = ast.literal_eval("[1,2,3]")
@Sid asks an important question in the comments:
Why not use eval()
as it is baked in and would not require the import?
While it is technically true that:
foo = eval("[1,2,3]")
also produces the desired result in this case, @AndyLester importantly reminds us that eval()
can be dangerous. Specifically eval()
allows for execution of code not just parsing of literals. If we imagine that the following could be any arbitrary block of python and someone could pollute our input with it:
"print('Here be Dragons')"
Then the first two methods will throw exceptions:
foo = json.loads("print('Here be Dragons')")
>>>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
and
foo = ast.literal_eval("print('Here be Dragons')")
>>>ValueError: malformed node or string:
While the third does
foo = eval("print('Here be Dragons')")
>>>Here be Dragons
our input was executed (dangerous) rather than simply parsed and worse, foo
also is still None
as print()
has no return value.
This will correctly parse your list
k = '[1,2,3]'
list(map(lambda x: int(x), k[1:-1].split(',')))
Yields:
[1, 2, 3]