I get this string for example:
s = '[1,0],[3,5],[5,6]'
I want to convert it to list.
If I do:
s.split("[*,*]")
then it doesn't work
I want to get this:
[[1,0],[3,5],[5,6]]
I get this string for example:
s = '[1,0],[3,5],[5,6]'
I want to convert it to list.
If I do:
s.split("[*,*]")
then it doesn't work
I want to get this:
[[1,0],[3,5],[5,6]]
You might use literal_eval
from ast
module (part of standard library) for this task as follows
import ast
s = '[1,0],[3,5],[5,6]'
lst = list(ast.literal_eval(s))
print(lst)
output
[[1, 0], [3, 5], [5, 6]]
Note that s
is literal for python's tuple
so I used list
for conversion into desired structure.
If the input format is really fixed :
out = [list(map(int, w.split(","))) for w in s[1:-1].split("],[")]
this may be faster but this may be less robust depending on input strict format than a real parsing solution like literal_eval
>>> import ast
>>> ast.literal_eval('[1,0],[3,5],[5,6]')
([1, 0], [3, 5], [5, 6])
literal_eval
is more secure than eval
in that it contains some logic to only actually evaluate valid literals.
Converting the result to a list()
left as an exercise. (Hint hint.)