我有一个字符串,像这样:"[['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中的列表?
发布评论