python重要函数eval

梦想的初衷 提交于 2020-01-06 14:12:25

1.参数会作为一个 Python 表达式(从技术上说是一个条件列表)被解析并求值

>>> x = 1
>>> eval('x+1')
2

2.去除字符串两边的引号

>>> a='"srting"'
>>> print(a)
"srting"
>>> b=eval(a)
>>> print(b)

srting
也可以用

>>> a.strip('"')
'srting'

3.字符串转字典

>>> a= "{'name':'linux','age':18}"
>>> type(a)
<type 'str'>
>>> b=eval(a)
>>> b
{'age': 18, 'name': 'linux'}
>>> type(b)
<type 'dict'>

4.传递全局变量

>>> a= "{'name':'linux','age':age}"
>>> b=eval(a,{"age":1822})
>>> b
{'age': 1822, 'name': 'linux'}
>>> type(b)
<type 'dict'>

5.传递本地变量

>>> a= "{'name':'linux','age':age}"
>>> age=18
>>> b=eval(a,{"age":1822},locals())
>>> b
{'age': 18, 'name': 'linux'}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!