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

您所在的位置:网站首页 字典函数item 【Python】内置函数eval的用法(及str转为dict的三种方式:eval/json/exec)

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

2024-07-12 03:05| 来源: 网络整理| 查看: 265

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

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

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

(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

(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 The b1's result is None

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

 

 

 

 

 

 

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3