在Python3.x中,使打印工作类似于Python2(as语句)

2024-03-28 16:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道print函数是否可以像python 2和更早版本那样工作(不改变所有的语法)。

所以我有这样的说法:

print "hello world"

我喜欢在python 3中使用这种语法。我试过导入库six,但这没有起到作用(仍然是语法错误)。


Tags: 函数版本helloworld语法print语法错误six
3条回答

您可以使用工具2to3是一个Automated Python 2 to 3 code translation,作为@Martijn Pieters♦ 告诉你:),你可以跳过一段旅程,扔掉旧的python,让修改工作进入python 3,我做了一个简单的例子如下:

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

#!python3

print 5

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

line 3
    print 5          ^
SyntaxError: Missing parentheses in call to 'print'

所以,你可以像这样通过终端转换它:

This is the important comand

$ 2to3 -w home/path_to_file/python2.py

-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:

文件看起来像:

#!python3

print(5)

您可以使用regex将python2的打印代码替换为python3:

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

replace with:
$1($2)$3

不,你不能。Python 3中的print语句已不存在;编译器不再支持它。

您可以让print()像Python 2中的函数一样工作;将它放在使用print的每个模块的顶部:

from __future__ import print_function

这将删除对Python 2中的print语句的支持,就像在Python 3中一样,您可以使用^{} function that ships with Python 2

six只能帮助桥接同时使用Python 2和3编写的代码;这包括将print语句替换为print()函数first

您可能想阅读Porting Python 2 Code to Python 3 howto;它还将告诉您更多类似from __future__的导入,以及介绍诸如ModernizeFuturize之类的工具,这些工具可以帮助自动修复Python 2代码,使其在python2和3上都能工作。

相关问题 更多 >