【Python】内置函数eval的用法(及str转为dict的三种方式:eval/json/exec)

Python eval() 函数

作用:eval() 函数用来执行一个字符串表达式,并返回表达式的值。

注意:计算指定表达式的值。也就是说它要执行的python代码只能是单个表达式(注意eval不支持任何形式的赋值操作),而不能是复杂的代码逻辑。

语法:eval(expression[, globals[, locals]])
参数:
expression -- 表达式。
globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

1.计算

下面来一个案例:

x = 2
print("The result of %s is %d" % ('5*x',3*x))  
print("The type of %s is %s" % ('5*x',type(eval( '5 * x' ))))  

结果为:

The result of 5*x is 6
The type of 5*x is <class 'int'>

可以看出,计算是返回一个结果。

2.str转为dict

(1)eval除了上面的用法,还有一个用法就是将str转为dict

exdata='{"name":"xiaoli","sex":"1"}'
print("The result of is %s" % (eval(exdata)))
print ("The result of is %s" % (type(eval(exdata))))

结果为:

The result of is {'name': 'xiaoli', 'sex': '1'}
The result of is <class 'dict'>

(2)除了eval,还可以用json的方式

import json
c=json.loads(exdata)
print("The result of is %s" % (c))
print ("The result of is %s" % (type(c)))

结果为:

The result of is {'name': 'xiaoli', 'sex': '1'}
The result of is <class 'dict'>

(3)exec函数
函数的作用:
动态执行python代码。也就是说exec可以执行复杂的python代码,而不像eval函数那样只能计算一个表达式的值。

返回值:
exec函数的返回值永远为None。

exec('b='+exdata)
b1=exec('b='+exdata)
print("The result is %s" % (b))
print ("The result is %s" % (type(b)))
print("The b1's result is %s"% (b1))

结果为:

The result is {'name': 'xiaoli', 'sex': '1'}
The result is <class 'dict'>
The b1's result is None

以上就是几个函数的用法了~

发布了92 篇原创文章 · 获赞 125 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/Jarry_cm/article/details/98495718