为什么使用 from __future__ import print_function 会破坏 Python2 风格的打印? [英] Why does using from __future__ import print_function breaks Python2-style print?

查看:22
本文介绍了为什么使用 from __future__ import print_function 会破坏 Python2 风格的打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new at programming with python, and I am trying to print out with a separator and end but it is still giving me a syntax error.

我使用的是 python 2.7.

I am using 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 需要是你脚本中的第一行代码(除了下面提到的一些例外).其次,正如其他答案所说,您现在必须将 print 用作函数.这就是 from __future__ import print_function 的全部内容;将 print function 从 Python 3 引入 Python 2.6+.

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into 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__ 语句需要靠近文件的顶部,因为它们改变了语言的基本内容,因此编译器需要从一开始就知道它们.来自文档:

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

future 语句在编译时被识别和特殊处理时间:核心结构的语义变化通常是通过生成不同的代码来实现.甚至可能是这样新功能引入了新的不兼容语法(例如新的保留字),在这种情况下编译器可能需要解析模块不同.此类决定不能推迟到运行时.

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__ 语句之前的唯一内容是模块文档字符串、注释、空行和其他未来语句.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

这篇关于为什么使用 from __future__ import print_function 会破坏 Python2 风格的打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆