eval函数

来源:互联网 发布:C语言韩信点兵 编辑:程序博客网 时间:2024/06/09 18:46

eval 函数

将一个字符串作为 Python 表达式求值.


你可以传递一串文本, 简单的表达式, 或者使用

内建 Python 函数. 如 Example 1-17 所示.  
1.2.5.1. Example 1-17. 使用 eval 函数  
File: builtin-eval-example-1.py
 
def dump(expression):
    result = eval(expression)
    print expression, "=>", result, type(result)
 
dump("1")
dump("1.0")
dump("'string'")
dump("1.0 + 2.0")
dump("'*' * 10")

dump("len('world')")


eval 函数只针对简单的表达式. 如果要处理大块的代码, 你应该使用 compile
exec 函数

compile 函数会返回一个代码对象, 你可以使用 exec 语句执行它


Python 还提供了 execfile 函数, 一个从文件加载代码, 编译代码, 执行代码
的快捷方式.

原创粉丝点击