如何在python中水平打印“紧”点?

2024-09-28 16:20:49 发布

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

我有一个程序可以把进度打印到控制台。 每20步,它会打印10、20、30等步数,但在这一步内,它会打印一个点。这是使用print语句在末尾加逗号(python2.x)打印的

        if epoch % 10 == 0:
            print epoch,
        else:
            print ".",

不幸的是,我注意到这些点是分开打印的,就像这样:

^{pr2}$

我想把这个再紧一点,如下所示:

0.........10.........20.........30

在visualbasic语言中,如果在print语句的末尾添加分号而不是逗号,就可以得到这个表单。在Python中是否有类似的方法来实现,或者通过演练来获得更紧凑的输出?在

注意:

带着对所有回复者的感谢和尊敬,我注意到他们中的一些人认为“时代”的变化是及时发生的。实际上,它不是,因为它发生在完成一些迭代之后,这可能需要几秒钟到几分钟的时间。在


Tags: 方法程序语言表单if语句elseprint
3条回答
import itertools
import sys
import time


counter = itertools.count()


def special_print(value):
    sys.stdout.write(value)
    sys.stdout.flush()


while True:
    time.sleep(0.1)
    i = next(counter)
    if i % 10 == 0:
        special_print(str(i))
    else:
        special_print('.')

如果您想获得对格式的更多控制,则需要使用:

import sys
sys.stdout.write('.')
sys.stdout.flush()  # otherwise won't show until some newline printed

。。而不是print,或者使用python3打印函数。在以后的Python 2.x版本中,它可以作为将来的导入:

^{pr2}$

在Python 3中,可以传递关键字参数flush

print('.', end='', flush=True)

它与上面的sys.stdout的两行具有相同的效果。在

这里有一个可能的解决方案:

import time
import sys

width = 101

for i in xrange(width):
    time.sleep(0.001)
    if i % 10 == 0:
        sys.stdout.write(str(i))
        sys.stdout.flush()
    else:
        sys.stdout.write(".")
        sys.stdout.flush()

sys.stdout.write("\n")

相关问题 更多 >