在不使用Eval的情况下将字符串转换为Python中的列表? [英] Convert String to List in Python Without Using Eval?

查看:287
本文介绍了在不使用Eval的情况下将字符串转换为Python中的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,像这样:"[['Cheese', 72], ['Milk', 45], ['Bread', 22]]".

I have a string, something like this: "[['Cheese', 72], ['Milk', 45], ['Bread', 22]]".

我想将其转换为列表.我知道我可以使用eval(string)来获取列表,但是eval令我感到恐惧,因为它可能会造成灾难(并且因为我可以获取非列表作为有效输出).还有另一种更安全的方式将此字符串转换为列表吗?我知道这是一个列表,所有不是列表的数据都是无效数据(应该检查和/或抛出错误).

I want to convert this to a list. I know I can use eval(string) to get the list, but eval scares me because of its potential for catastrophe (and because I can get a non-list as valid output). Is there another saner/safer way to turn this string into a list? I know it's a list and anything that isn't a list is invalid data (and should be checked for and/or throw an error).

推荐答案

如果坚持这样做,则可以使用ast.literal_eval函数.

If you insist on doing it this way, you can use the ast.literal_eval function.

>>> import ast
>>> foo = "[['Cheese', 72], ['Milk', 45], ['Bread', 22]]"
>>> ast.literal_eval(foo)
[['Cheese', 72], ['Milk', 45], ['Bread', 22]]

我确定其他人会告诉您您可能做错了什么,或者使用像JSON这样的库来传输像这样的任意数据结构,我不会反对.

I'm sure others will tell you that you're likely doing something wrong, or to use a library like JSON to transport arbitrary data structures like this one, and I wouldn't disagree.

这篇关于在不使用Eval的情况下将字符串转换为Python中的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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