eval(str)函数很强大,官方解释为:将字符串str当成有效的表达式来求值并返回计算结果。所以,结合math当成一个计算器很好用。
eval()函数常见作用有:
1、计算字符串中有效的表达式,并返回结果
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
2、将字符串转成相应的对象(如list、tuple、dict和string之间的转换)
>>> 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)
3、将利用反引号转换的字符串再反转回对象
>>> 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]