004、eval 和 ast.literal_eval 的区别

参考资料:https://blog.csdn.net/nanhuaibeian/article/details/102143356

 

 

一、eval 和 ast.literal_eval 的区别

1、eval在去除最外层引号时,能自动运算 ;ast.literal_eval 不能自动运算 ;

2、eval函数不安全,ast.literal_eval 安全;

3、相同点:都不能对 null 处理 ;他们都能对 python对象的数据类型处理 ;

如果有运算时用eval,否则用 ast.literal_eval;

 

 

 

演示代码如下:

# -*- coding:utf-8 -*-
# Author:  Sky
# Email:   2780619724@qq.com
# Time:    2021/9/5 16:47
# Project: Future_Loan_day16
# Module:  关于eval函数和literal_eval函数.py

import ast

# eval 函数不能转化 null, 转换时报错:NameError: name 'null' is not defined
# str_old = '[{"expr":"$.msg","expected":null,"type":"eq"}]'
# str_new = eval(str_old)
# print(str_new)

# eval 函数可以转 None,即能操作python的数据类型。——————OK
str_old_1 = '[{"expr":"$.msg","expected":None,"type":"eq"}]'
str_new_1 = eval(str_old_1)
print(str_new_1)


# eval函数在去掉引号的时候,会自动进行运算——————OK
# 执行结果:[{'expr': '$.msg', 'expected': 300, 'type': 'eq'}]
str_old_2 = '[{"expr":"$.msg","expected":100+200,"type":"eq"}]'
str_new_2 = eval(str_old_2)
print(str_new_2)


# literal_eval 能转化 None,即能操作python的数据类型。——————OK
str_old_3 = '[{"expr":"$.msg","expected":None,"type":"eq"}]'
str_new_3 = ast.literal_eval(str_old_3)
print(str_new_3)


# literal_eval 不能转化 null, 转换时报错:ValueError: malformed node or string:
# str_old_4 = '[{"expr":"$.msg","expected":null,"type":"eq"}]'
# str_new_4 = ast.literal_eval(str_old_4)
# print(str_new_4)


# 100+200 不能运算,转换时报错:ValueError: malformed node or string:
# str_old = '[{"expr":"$.msg","expected":100+200,"type":"eq"}]'
# str_new = ast.literal_eval(str_old)
# print(str_new)

执行结果如下:

D:\SkyWorkSpace\WorkSpace\API_test\lm\Future_Loan\Future_Loan_day16\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/API_test/lm/Future_Loan/Future_Loan_day16/相关知识点学习/关于eval函数和literal_eval函数.py
[{'expr': '$.msg', 'expected': None, 'type': 'eq'}]
[{'expr': '$.msg', 'expected': 300, 'type': 'eq'}]
[{'expr': '$.msg', 'expected': None, 'type': 'eq'}]

Process finished with exit code 0

 

posted @ 2021-09-05 17:37  空-山-新-雨  阅读(284)  评论(0编辑  收藏  举报