内置函数_eval

eval功能:将字符串str当成有效的表达式来求值并返回计算结果。

  语法: eval(source[, globals[, locals]]) -> value

  参数说明:

                 expression(sourse) -- 字符串表达式。也即,再写该表达式时不能忘记引号“ ”

                                                 =语句字符串

                 globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。

                             = 全局变量,若有,必须是字典。

                  locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

                            = 局部变量,若有,必须是字典,若无,则等同于globals

      返回值:返回表达式expression执行结果

可以把list,tuple,dict和string相互转化。

#字符串转换成列表

>>>a = "[1,2,3,4,5,6,7]"
>>>type(a)
<type 'str'>
>>> a = eval(a)
>>> print (a)
[1,2,3,4,5,6,7]
>>> type(a)
<type 'list'>

#字符串转换成字典

>>> a = "{1: 'a', 2: 'b',3:’c’}"
>>> type(a)
<type 'str'>
>>> a = eval(a)
>>> print (a)
{1: 'a', 2: 'b', 3:’c’}
>>> type(a)
<type 'dict'>

#字符串转换成元组

>>> a = "(1,2,3,4,5,6,7)"
>>> type(a)
<type 'str'>
>>>a= eval(a)
>>> print (a)
(1,2,3,4,5,6,7)
>>> type(a)
<type 'tuple'>

实例练习:

x = 100
y = 200
ls = {"x":1,"y":2}
gs = {"x":3,"y":4}

print("-----globals,locals均提供-----")
a = eval("x+y",ls,gs) # globals, locals均提供
print("a =",a) #a = 7
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"])) #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"])) #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y)) #x = 100, y = 200

print("-----globals提供-----")
b = eval("x+y",ls)
print("b =",b) #b = 3
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"])) #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"])) #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y)) #x = 100, y = 200

print("-----globals提供,local为None相当于不提供-----")
c = eval("x+y",ls,None)
print("c =",c) #c = 3
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"])) #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"])) #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y)) #x = 100, y = 200

print("-----globals为None,相当于不提供, locals提供-----")
d = eval("x+y",None,gs)
print("d =",d) #d = 7
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"])) #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"])) #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y)) #x = 100, y = 200

执行结果:

-----globals,locals均提供-----
a = 7
ls[x] = 1,ls[y] = 2
gs[x] = 3,gs[y] = 4
x = 100, y = 200
-----globals提供-----
b = 3
ls[x] = 1,ls[y] = 2
gs[x] = 3,gs[y] = 4
x = 100, y = 200
-----globals提供,local为None相当于不提供-----
c = 3
ls[x] = 1,ls[y] = 2
gs[x] = 3,gs[y] = 4
x = 100, y = 200
-----globals为None,相当于不提供, locals提供-----
d = 7
ls[x] = 1,ls[y] = 2
gs[x] = 3,gs[y] = 4
x = 100, y = 200
posted @ 2019-01-18 14:42  阳光宝贝-沐沐  阅读(320)  评论(0编辑  收藏  举报