简体   繁体   中英

Convert Array formatted as a string - Python

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 using

received.split(",")

however it splits up the arrays inside the array.

How would I go about converting the string to an array?

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM