python - 为什么使用 from __future__ import print_function 会破坏 Python2 样式的打印?

标签 python python-2.7 loops vim python-import

我是使用 python 编程的新手,我试图用分隔符和结尾打印出来,但它仍然给我一个语法错误。

我正在使用 python 2.7。

这是我的代码:

from __future__ import print_function
import sys, os, time

for x in range(0,10):
    print x, sep=' ', end=''
    time.sleep(1)

这是错误:

$ python2 xy.py
  File "xy.py", line 5
    print x, sep=' ', end=''
          ^
SyntaxError: invalid syntax
$

最佳答案

首先,from __future__ import print_function 必须是脚本中的第一行代码(除了下面提到的一些异常(exception)情况)。其次,正如其他答案所说,您现在必须使用 print 作为函数。这就是 from __future__ import print_function; 的全部意义所在。将 print function 从 Python 3 引入 Python 2.6+。

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ 语句需要靠近文件顶部,因为它们改变了语言的基本内容,因此编译器需要从一开始就知道它们。来自 the documentation :

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

文档还提到,可以在 __future__ 语句之前的唯一内容是模块文档字符串、注释、空行和其他 future 语句。

关于python - 为什么使用 from __future__ import print_function 会破坏 Python2 样式的打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32032697/

相关文章:

java - 这些是嵌套循环吗? java

python - 如何在 Python 脚本中获得导入类的相同作用域?

python - 使用 argparse 解析字符串

python - 使用 __init__ 为四个向量创建一个类

python - 如何动态构造闭包的命名空间 "pythonically"

python - 在路由之前修改 flask url

python - 在django-tastypie中,选择可以显示在schema中吗?

python - 在远程主机上运行脚本并查看输出

sql - 如何在postgresql中插入循环

c - C 编程新手,需要指导