python function eval

1. The parameters as a Python expression (technically is a list of conditions) is parsed and evaluated

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

2. Remove quotes around the string

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

You can also use

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

3. String turn Dictionary

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

4. global variable transmission

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

The local variable transmission

>>> a= "{'name':'linux','age':age}"
>>> age=18
>>> b=eval(a,{"age":1822},locals())
>>> b
{'age': 18, 'name': 'linux'}

Guess you like

Origin www.cnblogs.com/hello-wei/p/12134053.html