273

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

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

3 回答 3

339

在 Python 3 中,print 变成了一个函数。这意味着您现在需要包含括号,如下所述:

print("Hello World")
于 2009-05-05T21:21:18.877 回答
49

看起来您正在使用 Python 3.0,其中print 已变成可调用函数而不是语句。

print('Hello world!')
于 2009-05-05T21:21:24.880 回答
30

因为在 Python 3 中,print statement已被替换为print() function, 关键字参数,以替换旧 print 语句的大部分特殊语法。所以你必须把它写成

print("Hello World")

但是如果你在一个程序中编写这个并且有人使用 Python 2.x 试图运行它,他们会得到一个错误。为避免这种情况,导入打印功能是一个好习惯:

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 有什么新功能?

于 2014-10-27T12:35:26.673 回答