Python list string to list

后端 未结 6 1386
佛祖请我去吃肉
佛祖请我去吃肉 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]]
    
    0 讨论(0)
  • 2021-01-21 12:33

    You can do exactly what you asked for by using ast.literal_eval():

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

    However, you probably want to use a sane serialisation format like JSON in the first place, instead of relying on the string representation of Python objects. (As a side note, the string you have might even be JSON, since the JSON representation of this particular object would look identical to the Python string representation. Since you did not mention JSON, I'm assuming this is not what you used to get this string.)

    0 讨论(0)
  • 2021-01-21 12:37

    You want to use ast.literal_eval:

    import ast
    s= "[7, 9, 41, [32, 67]]"
    print ast.literal_eval(s)
    # [7, 9, 41, [32, 67]]
    
    0 讨论(0)
  • 2021-01-21 12:38

    It is another answer, But I don't suggest you.Because exec is dangerous.

    >>> s= "[7, 9, 41, [32, 67]]"
    >>> try:
    ...   exec 'l = ' + s
    ...   l
    ... except Exception as e:
    ...   e
    [7, 9, 41, [32, 67]]
    
    0 讨论(0)
  • 2021-01-21 12:41

    Use: package ast: function : literal_eval(node_or_string)

    http://docs.python.org/library/ast.html#module-ast

    0 讨论(0)
  • 2021-01-21 12:46

    why not use eval()?

    >>> s = "[7, 9, 41, [32, 67]]"
    >>> eval(s)
    [7, 9, 41, [32, 67]]
    
    0 讨论(0)
提交回复
热议问题