Convert string to nested structures such as a list

I have a line 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 a much cleaner approach to this?

+3


source to share


2 answers


First, don't name the variable str

as it shadows the inline.

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 refer to the last 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'}]]

      

+4


source


Use eval

but this is not good practice



eval("[[1, 2], [2.0, 0.3], ['a', 'b']]")
[[1, 2], [2.0, 0.3], ['a', 'b']]

      

+2


source







All Articles