Python eval()函数的使用

版权声明:码字不易,且看且珍惜!交流:Wechat: suihailiang0816 QQ: 931762054 转载并修改内容请与我联系 https://blog.csdn.net/weixin_41010198/article/details/89336626


切记: eval()函数的第一个参数的类型是字符串


一、官网给出的定义

eval(str)函数很强大,官方解释为:将字符串str当成有效的表达式来求值并返回计算结果。所以,结合math当成一个计算器很好用。

def eval(*args, **kwargs): # real signature unknown
    """
    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.
    """
    pass

1、eval() 方法的语法:


eval(expression[, globals[, locals]])

参数:

  • expression – 表达式。
  • globals – 变量作用域,全局命名空间,如果设置属性不为None的话,则必须是一个字典对象
  • locals – 变量作用域,局部命名空间,如果设置属性不为None的话,可以是任何映射(map)对象

返回值:
返回表达式计算结果。

二、eval的作用

1、计算字符串中有效的表达式,并返回结果

注意:
eval 的表达式一定是 字符串

>>> x1 = eval("pow(2,4)")
>>> x1
16
>>> type(x1)
<class 'int'>
>>> x2 = eval("2+6")
>>> x2
8
>>> type(x2)
<class 'int'>
>>> x3 = eval("8/4")
>>> x3
2.0
>>> type(x3)
<class 'float'>

2、将字符串转成相应的对象(如list、tuple、dict和string之间的转换)

  1. 字符串转换成列表数据结构
>>> x1 = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> x1
'[[1,2], [3,4], [5,6], [7,8], [9,0]]'
>>> x2 = eval(x1)
>>> x2
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> x1 = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> x1
'[[1,2], [3,4], [5,6], [7,8], [9,0]]'
>>> type(x1)
<class 'str'>
>>> x2 = eval(x1)
>>> x2
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> type(x2)
<class 'list'>
  1. 字符串转换成字典数据结构
>>> x1 = "{'name': 'Tom', 'age': 23}"
>>> x1
"{'name': 'Tom', 'age': 23}"
>>> type(x1)
<class 'str'>
>>> x2 = eval(x1)
>>> x2
{'name': 'Tom', 'age': 23}
>>> type(x2)
<class 'dict'>

三、eval()使用globals参数

可以在字典中定义未知数的值

>>> a = eval("x+23", {"x": 17})
>>> a
40
>>> b = eval("a + b", {"a": 13, "b": 7})
>>> b
20

猜你喜欢

转载自blog.csdn.net/weixin_41010198/article/details/89336626