Print in one line dynamically

后端 未结 20 3237
梦谈多话
梦谈多话 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-21 23:46

    Use print item, to make the print statement omit the newline.

    In Python 3, it's print(item, end=" ").

    If you want every number to display in the same place, use for example (Python 2.7):

    to = 20
    digits = len(str(to - 1))
    delete = "\b" * (digits + 1)
    for i in range(to):
        print "{0}{1:{2}}".format(delete, i, digits),
    

    In Python 3, it's a bit more complicated; here you need to flush sys.stdout or it won't print anything until after the loop has finished:

    import sys
    to = 20
    digits = len(str(to - 1))
    delete = "\b" * (digits)
    for i in range(to):
       print("{0}{1:{2}}".format(delete, i, digits), end="")
       sys.stdout.flush()
    

提交回复
热议问题