【问题标题】:Syntax error on print with Python 3 [duplicate]使用 Python 3 打印时出现语法错误 [重复]
【发布时间】:2018-05-21 18:23:18
【问题描述】:

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

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

【问题讨论】:

  • 提示:对于python 2.7+中的兼容性代码,请将其放在模块的开头:from __future__ import print_function
  • ...import print_function 似乎不起作用,您需要更改打印语句中的某些内容吗?还是应该导入?
  • 作为记录,这种情况将在 Python 3.4.2 中收到一条自定义错误消息:stackoverflow.com/questions/25445439/…
  • 2to3 是一个 Python 程序,它读取 Python 2.x 源代码并应用一系列修复程序将其转换为有效的 Python 3.x 代码更多信息可以在这里找到:[Python 文档:自动化 Python 2对3码翻译](docs.python.org/2/library/2to3.html)
  • 将其作为@ncoghlan 的其他帖子的欺骗而关闭,因为 1. 它有一个更全面的答案 2. 它已更新以匹配最新的错误。

标签: python python-3.x


【解决方案1】:

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

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)!

来源:What’s New In Python 3.0?

【讨论】:

    【解决方案2】:

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

    print('Hello world!')
    

    【讨论】:

      【解决方案3】:

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

      print("Hello World")
      

      【讨论】:

        猜你喜欢
        • 2015-07-23
        • 2011-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多