Python 3 中 print 的语法错误

274 投票
3 回答
272836 浏览
提问于 2025-04-15 11:25

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

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

3 个回答

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的新特性

49

看起来你正在使用Python 3.0版本,在这个版本中,print变成了一个可以调用的函数,而不是之前的语句

print('Hello world!')
339

在Python 3中,print变成了一个函数。这意味着你现在需要加上括号,就像下面提到的那样:

print("Hello World")

撰写回答