如何避免python中的eval进行字符串转换? [英] how to avoid eval in python for string conversion?
问题描述
我遇到了一个评估问题,我想向您提出建议,我知道评估错了,我想避免这种情况,但我不知道如何...
I'm confronted with an "eval" problem and I would like your advice, I know eval is wrong and I wish to avoid it but I don't know how...
我在数据库中存储了一些python对象,它们以字符串形式存储,并使用eval将它们转换为实际对象。例如,我的对象可以是一些简单的字符串,例如 [[2,1,3,4]或 [[[None,None],None] –它们对应于不同类型的对象,它们不遵循常见的模式。我必须像现在一样将它们存储为人类可读的对象。
I have some python objects stored in a database, they are stored as strings and I transform them into actual objects with eval. As an example, my objects could be some simple strings like "[2,1,3,4]" or "[[None,None],None]" -- they correspond to different types of object, they don't follow a common pattern. I have to store them as human-readable objects as they are now.
我的问题是在这种情况下如何避免评估?我不想为每个对象编写一个解析器。
My problem is how to avoid eval in this case ? I don't want to write a parser for each object.
如果我必须使用eval,我该如何清理这些字符串,以免它们使人讨厌?
If I do have to use eval, how do I clean up these strings so that they don't do anything nasty ?
推荐答案
使用 ast.literal_eval :
In [9]: import ast
In [10]: ast.literal_eval("[2,1,3,4]")
Out[10]: [2, 1, 3, 4]
这篇关于如何避免python中的eval进行字符串转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!