python eval()内置函数

python有一个内置函数eval(),可以将字符串进行运行。

通过help(eval)查看帮助文档

Help on built-in function eval in module builtins:

eval(source, globals=None, locals=None, /)
    Evaluate the given source in the context of globals and locals.
    
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

eval(source,globals=None,locals= None)

eval()函数默认是没有globals,locals,

如果提供则globals属性必须是一个字典dict类型,而locals 可以是任意映射

一般使用input函数,是str类型,如果进行数值运算,需要进行类型转化

a = input("Enter a number:
")

从键盘输入一个数值

a = 2

type(a)

为str类型

而 使用eval()内置函数

 a = eval(input("enter a number:
"))

type(a)
<class 'int'>

则为int。

eval()函数可以将字符串str当成有效的表达式来求值并返回计算结果

昨天学习碰见一个题目,给做错了,现在记录一下。

number = eval('5'+'1*2')  # 7是错误,正确答案是102

想当然的选择了答案是7,这个是错误的。

正确答案是:102.

因为这个eval()函数内有两个字符串"5"和"1*2",所以括号内首先做字符串连接,变成一个新的字符串"51*2",eval去掉双引号后,才能进行算数运算,得到数字102

再举个例子

number2 = eval('1'+'2*3'+'4*5')
# number2的值
print(number2)
2040

先拼接字符串,"12 *34*5"然后再去掉双引号进行算数运算,得到12*34*5=2040

eval()有一个坏处就是不太安全,如果用户输入一些字符串是恶意代码,则对系统不好,则需要使用

使用ast.literal_eval,

这个目前还没有用到,后续研究后进行总结。

每天进步一点
原文地址:https://www.cnblogs.com/hamish26/p/10168088.html