Print in one line dynamically

后端 未结 20 3215
梦谈多话
梦谈多话 2020-11-21 23:32

I would like to make several statements that give standard output without seeing newlines in between statements.

Specifically, suppose I have:

for it         


        
相关标签:
20条回答
  • 2020-11-22 00:04

    Change print item to:

    • print item, in Python 2.7
    • print(item, end=" ") in Python 3

    If you want to print the data dynamically use following syntax:

    • print(item, sep=' ', end='', flush=True) in Python 3
    0 讨论(0)
  • 2020-11-22 00:08

    To make the numbers overwrite each other, you can do something like this:

    for i in range(1,100):
        print "\r",i,
    

    That should work as long as the number is printed in the first column.

    EDIT: Here's a version that will work even if it isn't printed in the first column.

    prev_digits = -1
    for i in range(0,1000):
        print("%s%d" % ("\b"*(prev_digits + 1), i)),
        prev_digits = len(str(i))
    

    I should note that this code was tested and works just fine in Python 2.5 on Windows, in the WIndows console. According to some others, flushing of stdout may be required to see the results. YMMV.

    0 讨论(0)
提交回复
热议问题