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
目录
相关文章
|
1天前
|
Python
全网最适合入门的面向对象编程教程:Python函数方法与接口-函数与方法的区别和lamda匿名函数
【9月更文挑战第15天】在 Python 中,函数与方法有所区别:函数是独立的代码块,可通过函数名直接调用,不依赖特定类或对象;方法则是与类或对象关联的函数,通常在类内部定义并通过对象调用。Lambda 函数是一种简洁的匿名函数定义方式,常用于简单的操作或作为其他函数的参数。根据需求,可选择使用函数、方法或 lambda 函数来实现代码逻辑。
|
14天前
|
Python
python 函数
【9月更文挑战第4天】python 函数
34 5
|
20天前
|
Python
Python 中 help() 和 dir() 函数的用法
【8月更文挑战第29天】
18 5
|
21天前
|
Python
12类常用的Python函数
12类常用的Python函数
|
21天前
|
Python
python中getattr函数 hasattr函数
python中getattr函数 hasattr函数
|
14天前
|
数据采集 自然语言处理 数据挖掘
python查询汉字函数
简洁、高效、易懂的代码对于提高开发效率与项目质量至关重要,并且对于维持代码的可读性和可维护性也有着很大帮助。选择正确的工具和方法可以大幅提升处理中文数据的效率。在编写用户定义函数时,明确函数的功能与返回值类型对于函数的复用和调试也同样重要。当涉及到复杂的文本处理或数据分析时,不宜过分依赖单一的工具或方法,而应根据具体需求灵活选择和组合不同的技术手段。
22 0
WK
|
15天前
|
图计算 开发者 Python
python中的函数有哪些用途
Python中的函数具有多种用途,它们极大地增强了代码的复用性、可读性和可维护性。
WK
10 0
|
20天前
|
Python
Python 中的 Lambda 函数是什么?
【8月更文挑战第29天】
8 0
|
21天前
|
索引 Python
Python最常用的函数、基础语句有哪些?你都知道吗
Python最常用的函数、基础语句有哪些?你都知道吗
|
Python
12.1、python内置函数——eval、exec、compile
内置函数——eval、exec、compile eval() 将字符串类型的代码执行并返回结果 print(eval('1+2+3+4')) exec()将自字符串类型的代码执行 print(exec("1+2+3+4"))exec("print('hello,world')") code = ''' import os print(os.
1108 0