为什么包含“end=”参数的python print语句在whileloop中的行为不同?

2024-04-29 21:07:45 发布

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

我在MacOSX上运行Python2.7.3版本。

考虑这段代码:

from __future__ import print_function
import time
x = 0
while x < 5:
    print(x)
    x += 1
    time.sleep(1)

如果我运行这个脚本,我会观察到预期的输出:数字04,每个数字后面附加一个\n字符。此外,每一个数字都会在暂停一秒钟后显示。

0
1
2
3
4

现在考虑这个代码块:

from __future__ import print_function
import time
x = 0
while x < 5:
    print(x, end='')
    x += 1
    time.sleep(1)

输出是我所期望的,01234没有\n的,但是计时是意外的。该进程不会在一秒钟的暂停后显示每个数字,而是等待四秒钟,然后显示所有五个数字。

为什么print('string')的行为与while循环中的print('string', end='')不同?有没有办法显示没有换行符的字符,一次一秒?我试过sys.stdout.write(str(x)),但它的行为与print(end='')相同。


Tags: 代码fromimport版本stringtimefunctionfuture