Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to nested structures like list

I have a string like

str_sample = "[[1, 2], [2.0, 0.3], ['a', 'b', [None, (1, 3)], {'c': 'd'}]]"

I am currently using:

exec("str2list_sample = "+ str_sample)

Is there any much more cleaner approach of doing this?

like image 606
Gurupad Hegde Avatar asked Mar 15 '23 19:03

Gurupad Hegde


2 Answers

Firstly don't name your variable str as it shadows the built-in.

To solve your problem you can use ast.literal_eval

>>> a = "[[1, 2], [2.0, 0.3], ['a', 'b']]"
>>> import ast
>>> ast.literal_eval(a)
[[1, 2], [2.0, 0.3], ['a', 'b']]

To address your latest edit

>>> str_sample = "[[1, 2], [2.0, 0.3], ['a', 'b', [None, (1, 3)], {'c': 'd'}]]"
>>> ast.literal_eval(str_sample)
[[1, 2], [2.0, 0.3], ['a', 'b', [None, (1, 3)], {'c': 'd'}]]
like image 98
Bhargav Rao Avatar answered Mar 30 '23 12:03

Bhargav Rao


Use eval, but this is not a good practice

eval("[[1, 2], [2.0, 0.3], ['a', 'b']]")
[[1, 2], [2.0, 0.3], ['a', 'b']]
like image 21
Namit Singal Avatar answered Mar 30 '23 13:03

Namit Singal