在python 3.x中使打印工作像在python 2中一样(作为语句)

pau*_*l23 12 python function python-2.7 python-3.3

我想知道是否可以使用print函数(不改变语法),就像在python 2和更早版本中一样.

所以我的声明如下:

print "hello world"
Run Code Online (Sandbox Code Playgroud)

我喜欢在python 3中使用该语法.我已经尝试导入库six但是没有做到这一点(仍然是语法错误).

Mar*_*ers 9

你不能.该print声明没有了在Python 3; 编译器不再支持它了.

可以print()类似的函数工作在Python 2 ; 把它放在每个使用的模块的顶部print:

from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)

这将删除对printPython 2中语句的支持,就像它在Python 3中消失一样,并且您可以使用print()Python 2附带函数.

six只能帮助桥接用Python 2和3编写的代码; 包括首先printprint()函数替换语句.

您可能希望阅读Porting Python 2 Code to Python 3 howto ; 它还会告诉你更多这样的from __future__导入,以及介绍诸如ModernizeFuturize之类的工具,这些工具可以帮助自动修复Python 2代码,以便在Python 2和3上工作.

  • 真可惜 - 我需要执行第三方提供的代码,我真的不喜欢检查所有代码来更改所有这些打印:/。(你在这里描述的与我的问题相反:我确实在 python 3 中工作,但我需要运行由在 python 2 中工作的人编写的代码) (5认同)

Oli*_*erQ 9

您可以使用正则表达式将printPython 2的代码替换为Python 3:

Find:
(print) (.*)(\n)

Replace with:
$1($2)$3
Run Code Online (Sandbox Code Playgroud)


Dam*_*ero 5

您可以使用工具2to3Python 2到3自动代码转换,就像@Martijn Pieters吗?告诉:),您可以轻松地扔掉旧的python,并使所做的更改适用于python 3,下面我举一个简单的示例:

我创建了这个文件python2.py:

#!python3

print 5
Run Code Online (Sandbox Code Playgroud)

当我使用python运行它时,它显然显示:

line 3
    print 5          ^
SyntaxError: Missing parentheses in call to 'print'
Run Code Online (Sandbox Code Playgroud)

因此,您可以通过如下所示的终端对其进行转换:

这是重要的命令

$ 2to3 -w home/path_to_file/python2.py
Run Code Online (Sandbox Code Playgroud)

-w参数将写入文件,如果您只想查看将来的更改而不应用它们,则在不使用-w的情况下运行它。运行后它将显示类似

root: Generating grammar tables from /usr/lib/python2.7/lib2to3/PatternGrammar.txt
RefactoringTool: Refactored Desktop/stackoverflow/goto.py
--- Desktop/stackoverflow/goto.py   (original)
+++ Desktop/stackoverflow/goto.py   (refactored)
@@ -1,3 +1,3 @@
 #!python3

-print 5
+print(5)
RefactoringTool: Files that were modified:
Run Code Online (Sandbox Code Playgroud)

该文件将如下所示:

#!python3

print(5)
Run Code Online (Sandbox Code Playgroud)