Python eval()函数的使用

简介: Python 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
目录
相关文章
|
10天前
|
Python
python 函数
【9月更文挑战第4天】python 函数
33 5
|
16天前
|
Python
Python 中 help() 和 dir() 函数的用法
【8月更文挑战第29天】
18 5
|
17天前
|
Python
12类常用的Python函数
12类常用的Python函数
|
17天前
|
Python
python中getattr函数 hasattr函数
python中getattr函数 hasattr函数
|
17天前
|
算法 Python
python函数递归和生成器
python函数递归和生成器
|
10天前
|
数据采集 自然语言处理 数据挖掘
python查询汉字函数
简洁、高效、易懂的代码对于提高开发效率与项目质量至关重要,并且对于维持代码的可读性和可维护性也有着很大帮助。选择正确的工具和方法可以大幅提升处理中文数据的效率。在编写用户定义函数时,明确函数的功能与返回值类型对于函数的复用和调试也同样重要。当涉及到复杂的文本处理或数据分析时,不宜过分依赖单一的工具或方法,而应根据具体需求灵活选择和组合不同的技术手段。
19 0
WK
|
11天前
|
图计算 开发者 Python
python中的函数有哪些用途
Python中的函数具有多种用途,它们极大地增强了代码的复用性、可读性和可维护性。
WK
9 0
|
16天前
|
Python
Python 中的 Lambda 函数是什么?
【8月更文挑战第29天】
8 0
|
17天前
|
索引 Python
Python最常用的函数、基础语句有哪些?你都知道吗
Python最常用的函数、基础语句有哪些?你都知道吗
|
4月前
|
算法 Python 容器
Python编程 - 不调用相关choose库函数,“众数“挑选器、随机挑选器 的源码编程实现
Python编程 - 不调用相关choose库函数,“众数“挑选器、随机挑选器 的源码编程实现
63 0