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
  • 151,199
  • 17
  • 111
  • 216
Alex
  • 21
  • 3

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
  • 21,690
  • 3
  • 9
  • 19
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
  • 158,107
  • 27
  • 234
  • 292
1

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
  • 744
  • 7
  • 20