原文:https://blog.csdn.net/sun2333/article/details/82418326
1、eval可以字符串型的list,tuple,dict转变成原有的类型
(1)string <=> list
In [1]: s = ‘[1, 2, 3, 4]‘ In [2]: l = eval(s) In [3]: s Out[3]: ‘[1, 2, 3, 4]‘ In [4]: l Out[4]: [1, 2, 3, 4] In [5]: type(s) Out[5]: str In [6]: type(l) Out[6]: list
(2)string <=> tuple
In [9]: s = ‘(1, 2, 3)‘ In [10]: l = eval(s) In [11]: s Out[11]: ‘(1, 2, 3)‘ In [12]: l Out[12]: (1, 2, 3) In [13]: type(s) Out[13]: str In [14]: type(l) Out[14]: tuple
(3)string <=> dict
In [15]: s = "{‘key‘: ‘value‘}" In [16]: d = eval(s) In [17]: s Out[17]: "{‘key‘: ‘value‘}" In [18]: d Out[18]: {‘key‘: ‘value‘} In [19]: type(s) Out[19]: str In [20]: type(d) Out[20]: dict
2、ast.literal_eval:则会判断需要计算的内容计算后是不是合法的python类型,如果是则进行运算,否则就不进行运算
只会执行合法的python类型,会降低系统风险
原文地址:https://www.cnblogs.com/CXMS/p/12561507.html
时间: 2024-10-28 17:04:08