[英]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
. 使用
literal_eval
比eval
更安全。 From the docs: 从文档:
31.2.
31.2。 ast — Abstract Syntax Trees¶
ast —抽象语法树¶
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python expression.
安全地评估表达式节点或包含Python表达式的字符串。 The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
提供的字符串或节点只能由以下Python文字结构组成:字符串,数字,元组,列表,字典,布尔值和无。
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
这可用于安全地评估包含来自不受信任来源的Python表达式的字符串,而无需自己解析值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.