为什么使用“从未来导入打印”功能会破坏Python2样式的打印?

2024-04-26 05:50:29 发布

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

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

我正在使用Python2.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
$

Tags: 代码frompyimporttime编程sepend
1条回答
网友
1楼 · 发布于 2024-04-26 05:50:29

首先,from __future__ import print_function需要是脚本中的第一行代码(除了下面提到的一些异常)。其次,正如其他答案所说,现在必须使用print作为函数。这就是from __future__ import print_function;将Python 3中的print函数引入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__语句前面的只有模块docstring、注释、空行和其他将来的语句。

相关问题 更多 >