【问题标题】:How to print 'tight' dots horizontally in python?如何在python中水平打印“紧”点?
【发布时间】:2016-08-24 12:37:25
【问题描述】:

我有一个程序可以将其进度打印到控制台。 每 20 步,它会打印步数,例如 10 20 30 等,但在此范围内,它会打印一个点。这是使用带有逗号的 print 语句打印出来的 (python 2.x)

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

不幸的是,我注意到这些点彼此分开打印,如下所示:

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

我希望这个更严格,如下:

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

在 Visual Basic 语言中,如果我们在 print 语句的末尾添加一个分号而不是逗号,我们可以得到这种形式。在 Python 中是否有类似的方法可以做到这一点,或者通过演练来获得更严格的输出?

注意:

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

【问题讨论】:

  • 删除逗号意味着你会得到一个换行符而不是一个空格,所以不会做 OP 想要的。

标签: python printing console


【解决方案1】:

如果你想更好地控制格式,那么你需要使用:

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

.. 代替 print,或者使用 Python 3 打印函数。这可以在以后的 Python 2.x 版本中作为未来的导入使用:

from __future__ import print_function
print('.', end='')

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

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

和上面sys.stdout的两行效果一样。

【讨论】:

  • 感谢@Isogen74 的回答,Python3 打印功能的使用似乎更好,但是当我尝试它时,整个程序的每个打印语句都有大量错误。可以并排使用两个打印语句(来自 Py2 和 Py3)吗?
  • 不在同一个文件中 - “from future”将文件中“print”的含义从旧语义更改为新语义。
【解决方案2】:
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('.')

【讨论】:

    【解决方案3】:

    这是一个可能的解决方案:

    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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 2018-02-01
      • 2021-02-18
      相关资源
      最近更新 更多