eval(str)函数很强大,官方解释为:将字符串str当成有效的表达式来求值并返回计算结果。所以,结合math当成一个计算器很好用。
eval()函数常见作用有:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
Python 3.6.8 | Anaconda , Inc . | ( default , Dec 29 2018 , 19 : 04 : 46 )
Type 'copyright' , 'credits' or 'license' for more information
IPython 7.4.0 -- An enhanced Interactive Python . Type '?' for help .
In [ 1 ] : eval ( '1+1' )
Out [ 1 ] : 2
In [ 2 ] : eval ( 'pow(2,2)' )
Out [ 2 ] : 4
In [ 3 ] : n = 10
In [ 4 ] : eval ( 'n+1' )
Out [ 4 ] : 11
In [ 11 ] : def hello ( ) :
. . . : print ( 'hello' )
. . . :
In [ 12 ] : eval ( 'hello()' )
hello
In [ 13 ] : eval ( 'hello' ) ( )
hello
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> b = eval ( a )
>>> b
[ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] , [ 7 , 8 ] , [ 9 , 0 ] ]
>>> a = "{1:'xx',2:'yy'}"
>>> c = eval ( a )
>>> c
{ 1 : 'xx' , 2 : 'yy' }
>>> a = "(1,2,3,4)"
>>> d = eval ( a )
>>> d
( 1 , 2 , 3 , 4 )
|
1
2
3
4
5
6
7
8
9
10
11
|
>>> list1 = [ 1 , 2 , 3 , 4 , 5 ]
>>> ` list1 `
'[1, 2, 3, 4, 5]'
>>> type ( ` list1 ` )
< type 'str' >
>>> type ( eval ( ` list1 ` ) )
< type 'list' >
>>> a = eval ( ` list1 ` )
>>> a
[ 1 , 2 , 3 , 4 , 5 ]
|