python - 打印语句 python 2.7 上的语法无效

标签 python python-2.7

我有一些代码来测试我编写的其他代码(在 ipython 笔记本中)。

print_closest = lambda w, wl: print('{}: {} ({})'.format(w, *closest_match(w, wl)))

这是我的代码,它适用于 python 3 环境。但是,它不适用于 python 2.7。相反,它会在下面抛出一个错误。

print_closest = lambda w, wl: print('{}: {} ({})'.format(w, *closest_match(w, wl)))
                                      ^
SyntaxError: invalid syntax

我想对上面的代码进行更改,以便使其在 python2.7 环境以及 python3 环境下工作。

谁能告诉我怎么做吗?提前致谢。

最佳答案

在Python 2中,print是一条语句,而不是一个函数(作为一个函数,使用它将是一个表达式)。 lambda 只能包含表达式,不能包含完整语句。

也就是说,您可以在 Py2 上获得 Py3 print 功能。在要切换的模块中,将以下内容添加为文件中的第一行代码(在任何 shebang 或编码注释之后,在其他所有内容之前):

from __future__ import print_function

那个will make print a function as it is in Py3 .

关于python - 打印语句 python 2.7 上的语法无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40245669/

相关文章:

json - 使用 json.dumps 让 Python Flask 返回 application/json

javascript - Python/JavaScript/HTML 动态创建计算机网络图

python - 将变量从 Python 脚本传递到 tcl shell

python - Django:在查询集中相乘

python - 将 lxml 安装到 virtualenv

python - 拆分数据框中的字符串

python - 单击程序时遇到问题 - pyautogui

python - 引用数据框对象的索引和列?

python - 在nodejs pyshell中导入已安装的python包时出错

python - 从 dict 中检索对象,以便可以通过 json.dumps() 轻松转储该对象