1

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]]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Alex
  • 41
  • 4

3 Answers3

2

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.

Daweo
  • 31,313
  • 3
  • 12
  • 25
2

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

jmbarbier
  • 814
  • 8
  • 21
1
>>> 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.)

tripleee
  • 175,061
  • 34
  • 275
  • 318