Skip to main content
 首页 » 编程设计

python之在 Python 2.7 中返回打印函数

2025年05月04日8zhoujg

如何在 Python 2.7 中返回打印函数?在 Python 3 中,您可以键入 return print(True),但在 Python 2.7 中,当我尝试 return print True 时出现无效语法错误。我是 Python 的新手。

请您参考如下方法:

在 Python 2.x 中,print 不是一个函数,而是一个关键字。 可能的最佳解决方案是导入类似 3.x 的打印行为,如下所示:

from __future__ import print_function 
 
p = print         # now you can store the function reference to a variable 
p('I am a function now!') 
 
>>> I am a function now! 
 
def get_print(): 
    return print   # or return it :) 
 
get_print() 
 
>>> <function print>