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

使用Python 3打印时出现语法错误,python,python-3.x,Python,Python 3.x,为什么在Python3中打印字符串时会收到语法错误 >>> print "hello World" File "<stdin>", line 1 print "hello World" ^ SyntaxError: invalid syntax 打印“hello World” 文件“”,第1行 打印“hello World” ^ SyntaxError:无效语法 在Python 3中,打印。这意味着您现在需要

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

>>> print "hello World"
  File "<stdin>", line 1
    print "hello World"
                      ^
SyntaxError: invalid syntax
打印“hello World” 文件“”,第1行 打印“hello World” ^ SyntaxError:无效语法
在Python 3中,
打印
。这意味着您现在需要包括括号,如下所述:

print("Hello World")

看起来您使用的是Python 3.0,而不是一条语句

print('Hello world!')

因为在Python3中,
print语句
已被一个
print()函数
替换,该函数使用关键字参数替换旧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)!

来源:

提示:对于python 2.7+中的兼容代码,请将此放在模块开头:
来自uuu future\uuuu导入打印功能
…导入打印功能似乎不起作用,是否需要更改打印语句中的某些内容?或者导入应该这样做吗?为了记录在案,本例将在Python 3.4.2中获得一条自定义错误消息:2to3是一个Python程序,它读取Python 2.x源代码并应用一系列修复程序将其转换为有效的Python 3.x代码。更多信息可在此处找到:[Python文档:自动Python 2到3代码翻译]()以@ncoghlan对另一篇文章的欺骗来结束这篇文章,因为1。它有一个更全面的答案2。它会更新以匹配最新的错误。