转换格式为一个字符串数组 - 的Python [英] Convert Array formatted as a string - Python

查看:617
本文介绍了转换格式为一个字符串数组 - 的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是通过像这样的插座receving字符串

 ['[0,0,0],[0,0,0]']

我想它转换回一个数组。我已经尝试使用

  received.split()

但它分裂了阵列的阵列中。

我怎么会去的字符串转换为一个数组?


解决方案

 >>>进口AST
>>> S =['[0,0,0],[0,0,0]']
>>> S = ast.literal_eval(多个)
>>>小号
['[0,0,0]','[0,0,0]']
>>> S = [ast.literal_eval(分)在亚健康]
>>>小号
[0,0,0],[0,0,0]]

使用 literal_eval 评估更安全。从文档:


  

31.2。 AST - 抽象语法Trees¶


  
  

ast.literal_eval(node_or_string)


  
  

安全评估的前pression节点或含有一个Python前pression的字符串。字符串,数字,元组,列表,类型的字典,布尔无

:提供只能由以下的Python字面结构的字符串或节点
  
  

这可以用于包括Python前pressions安全评估字符串
      从无需解析值不可信来源自身。


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.

这篇关于转换格式为一个字符串数组 - 的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆