Python 3中的打印语句出现了语法错误。

274

为什么在Python 3中打印字符串时会收到语法错误?

>>> print "hello World"
  File "<stdin>", line 1
    print "hello World"
                      ^
SyntaxError: invalid syntax

18
为了使Python 2.7+版本兼容性更强,可以在模块开头加入以下代码:from __future__ import print_function。此代码的作用是将Python 3.x中的print函数引入到当前模块中,以便在Python 2.7+版本中使用。注意,此操作不会改变原有功能,只是提高了兼容性。 - Yauhen Yakimovich
...import print_function 似乎不起作用,你需要在打印语句中更改一些内容吗?还是导入应该自动完成? - RASMiranda
5
记录一下,在Python 3.4.2中,这个问题将会得到一个定制的错误信息:https://dev59.com/Sl8e5IYBdhLWcg3wucRT - ncoghlan
1
2to3是一个Python程序,可以读取Python 2.x源代码并应用一系列的修复程序将其转换为有效的Python 3.x代码。更多信息可以在此处找到:Python文档:自动化Python 2到3代码转换 - Oliver Sievers
将此关闭为 @ncoghlan 的另一个帖子的重复,因为1.它具有更全面的答案2.它已更新以匹配最新的错误。 - Bhargav Rao
3个回答

339
在Python 3中,print 变成了一个函数。这意味着现在需要像下面提到的那样包含括号:
print("Hello World")

49

30

因为在Python 3中,print语句已被替换为print()函数,使用关键字参数替换了旧的print语句的大部分特殊语法。因此,您需要将其编写为:

print("Hello World")

但是,如果您在程序中编写此代码,并且有人试图在使用Python 2.x的环境中运行它,将会出现错误。为了避免这种情况,最好导入print函数:

from __future__ import print_function

现在你的代码可以在2.x和3.x上运行。

还可以查看下面的示例,以熟悉print()函数。

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

来源:Python 3.0有什么新特性?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接