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
但是没有做到这一点(仍然是语法错误).
你不能.该print
声明没有了在Python 3; 编译器不再支持它了.
你可以做print()
类似的函数工作在Python 2 ; 把它放在每个使用的模块的顶部print
:
from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)
这将删除对print
Python 2中语句的支持,就像它在Python 3中消失一样,并且您可以使用print()
Python 2附带的函数.
six
只能帮助桥接用Python 2和3编写的代码; 包括首先print
用print()
函数替换语句.
您可能希望阅读Porting Python 2 Code to Python 3 howto ; 它还会告诉你更多这样的from __future__
导入,以及介绍诸如Modernize和Futurize之类的工具,这些工具可以帮助自动修复Python 2代码,以便在Python 2和3上工作.
您可以使用正则表达式将print
Python 2的代码替换为Python 3:
Find:
(print) (.*)(\n)
Replace with:
$1($2)$3
Run Code Online (Sandbox Code Playgroud)
您可以使用工具2to3是Python 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)