【问题标题】:python - print iteration number without new linepython - 打印没有换行的迭代号
【发布时间】:2014-12-18 08:42:24
【问题描述】:

我有一个循环:

for i in range(10):
    print i

然后打印出来:

1
2
...
8
9

好的

但我正在寻找制作一个 unique 线,以像这样为每次迭代实现:

for i in range(10):
    magic_print "this is the iteration " + i + " /10"

结果如下:

"this is the iteration <i> /10"

&lt;i&gt; 动态变化

谢谢!

【问题讨论】:

    标签: python printing iteration line


    【解决方案1】:

    据我了解您的问题,您想覆盖以前的打印并计数。看到这个答案:https://stackoverflow.com/a/5419488/4362607

    我根据 PM 2Ring 的建议编辑了答案。谢谢!

    import sys
    import time
    
    def counter():
        for x in range(10):
            print '{0}\r'.format(x),
            sys.stdout.flush()
            time.sleep(1)
        print
    
    counter()
    

    【讨论】:

    • 差不多。在print 语句之后,您可能需要sys.stdout.flush()。您可以将time.sleep(1) 放入循环中,这样我们就可以看到发生了什么。
    【解决方案2】:

    解决方案是 str 对象中的 format 函数

    for i in range(10):
        print "this is the iteration {} /10".format(i)
    

    【讨论】:

      猜你喜欢
      • 2011-04-05
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 2018-04-25
      • 2023-02-20
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多