Convert Array formatted as a string - Python

前端 未结 1 1809
悲&欢浪女
悲&欢浪女 2020-12-20 04:23

I am receving a string through a socket like so

\"[\'[0,0,0]\',\'[0,0,0]\']\"

I would like to convert it back to a array. I have tried usin

相关标签:
1条回答
  • 2020-12-20 04:38
    >>> import ast
    >>> s = "['[0,0,0]','[0,0,0]']"
    >>> s = ast.literal_eval(s)
    >>> s
    ['[0,0,0]', '[0,0,0]']
    >>> s = [ast.literal_eval(sub) for sub in s]
    >>> s
    [[0, 0, 0], [0, 0, 0]] 
    

    Using literal_eval is safer than eval. From the docs:

    31.2. ast — Abstract Syntax Trees¶

    ast.literal_eval(node_or_string)

    Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

    This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

    0 讨论(0)
提交回复
热议问题