eval(str) 函数很强大,官方解释:将字符串当成有效的表达式来求值并返回计算结果。
1.计算字符串中出现的有效表达式,并返回结果
>>> eval('1+2')
3 >>> eval('pow(2,3)')
8 >>> n=10 >>> eval('n-1')
9 >>> def hello(): ... print('hello') ... >>> eval('hello()')
hello >>> eval('hello')()
hello
2.将字符串转换成相应的对象
>>> a = "[[1,2],[3,4],[5,6],[7,8]]" >>> b = eval(a) >>> b [[1,2],[3,4],[5,6],[7,8]] >>> a = "{1:'xy',2:'cc'}" >>> c = eval(a) >>> c {1:'xy',2:'cc'} >>> a = "(1,2,3,4)" >>> d = eval(a) >>> d (1,2,3,4)