使用Python 3打印时出现语法错误

2024-04-26 22:40:12 发布

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

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

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

Tags: 字符串helloworldstdinlinefileprintsyntax
3条回答

看起来您正在使用Python 3.0,其中print has turned into a callable function而不是语句。

print('Hello world!')

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

print("Hello World")

但是,如果您在程序中编写它,并且有人使用Python2.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)!

来源:What’s New In Python 3.0?

在Python 3中,printbecame a function。这意味着您现在需要包括如下所述的括号:

print("Hello World")

相关问题 更多 >