0

can anyone help me with this convertion? I need a list from string.

x = [[1,2],[2.3,59]]
y = str(x)

backToList = list(y) 
backToList = ['[', '[', '1', ',', ' ', '2', ']', ',', ' ', '[', '2', '.', '3', ',', ' ', '5', '9', ']', ']']

I need to get this: backToList = [[1,2],[2.3,59]] Thx.

Fuk Yu
  • 173
  • 1
  • 9

1 Answers1

1

You want to use ast.literal_eval for this, which is safer than eval:

>>> x = [[1,2],[2.3,59]]
>>> y = str(x)
>>>
>>> import ast
>>> ast.literal_eval(y)
[[1, 2], [2.3, 59]]
brianpck
  • 8,084
  • 1
  • 22
  • 33
  • Thx, why is that safer? – Fuk Yu Nov 04 '16 at 14:42
  • @CrazyDeveloper In this case it doesn't make a difference, but `eval` has many vulnerabilities that can be exploited if executed on user input. See http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html – brianpck Nov 04 '16 at 15:43