教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 Python eval函数是什么?怎么使用?

Python eval函数是什么?怎么使用?

发布时间:2021-01-12   编辑:jiaochengji.com
教程集为您提供Python eval函数是什么?怎么使用?等资源,欢迎您收藏本站,我们将为您提供最新的Python eval函数是什么?怎么使用?资源

我们之前跟大家描述了在Python里面一些函数的不同使用,以及一些函数的潜藏使用技巧,可是大家有没有听说过,有一个函数一直被誉为最神奇的函数,神奇的地方在哪里?到底怎么神奇?请看下文。

关于eval():

将字符串string对象转化为有效的表达式参与求值运算返回计算结果

语法上:

调用的是:eval(expression,globals=None, locals=None)返回的是计算结果

其中:

1、expression是一个参与计算的python表达式

2、globals是可选的参数,如果设置属性不为None的话,就必须是dictionary对象了

3、locals也是一个可选的对象,如果设置属性不为None的话,可以是任何map对象了

4、python是用命名空间来记录变量的轨迹的,命名空间是一个dictionary,键是变量名,值是变量值。

下面简单演示一下eval()函数的使用:

#!usr/bin/env python
#encoding:utf-8
 
import math
 
 
def eval_test():
 l='[1,2,3,4,[5,6,7,8,9]]'
 d="{'a':123,'b':456,'c':789}"
 t='([1,3,5],[5,6,7,8,9],[123,456,789])'
 print '--------------------------转化开始--------------------------------'
 print type(l), type(eval(l))
 print type(d), type(eval(d))
 print type(t), type(eval(t))
 
if __name__=="__main__":
 eval_test()

测试结果输出如下:

--------------------------转化开始--------------------------------
<type 'str'> <type 'list'>
<type 'str'> <type 'dict'>
<type 'str'> <type 'tuple'>
[Finished in 0.2s]

以上就是这个神奇的函数用法,是不是感觉很奇特呢?学会的话,可以在自己的内容里填充使用哈~

您可能感兴趣的文章:
python里的eval是什么
php中eval()函数操作数组的方法
python eval() 怎么用
Python中eval有什么用
Python中eval与exec的使用及区别
python eval什么意思
python eval和exec的区别是什么
Python eval函数是什么?怎么使用?
python怎么输入整数
eval函数带来的危机你知道吗?

[关闭]
~ ~