Convert string to nested structures like list

前端 未结 2 1534
闹比i
闹比i 2021-01-19 11:27

I have a string like

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

I am currently using:



        
相关标签:
2条回答
  • 2021-01-19 12:21

    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'}]]
    
    0 讨论(0)
  • 2021-01-19 12:22

    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']]
    
    0 讨论(0)
提交回复
热议问题