Python list string to list

后端 未结 6 1385
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 11:51

I have a string:

s= \"[7, 9, 41, [32, 67]]\"

and I need to convert that string into a list:

l= [7, 9, 41, [32, 67]]
         


        
6条回答
  •  生来不讨喜
    2021-01-21 12:28

    Use the ast module, it has a handy .literal_eval() function:

    import ast
    
    l = ast.literal_eval(s)
    

    On the python prompt:

    >>> import ast
    >>> s= "[7, 9, 41, [32, 67]]"
    >>> ast.literal_eval(s)
    [7, 9, 41, [32, 67]]
    

提交回复
热议问题