在不使用Eval的情况下将字符串转换为Python中的列表?

编程入门 行业动态 更新时间:2024-10-27 20:27:15
本文介绍了在不使用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中的列表?

本文发布于:2023-10-25 22:31:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528305.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   情况下   列表   Eval

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!