当前位置: 动力学知识库 > 问答 > 编程问答 >

python - print that only prints one line

问题描述:

How would you make print only print one line each time like

for i in range(1,100)

print i

but then i would want it to print one line each time so it would be: 1 and then 1 would be erased then it would print 2 and so on.

网友答案:

like this?

import sys
import time
>>> for i in range(1, 100):
...     sys.stdout.write(str(i))
...     sys.stdout.flush()
...     time.sleep(0.2)
...     sys.stdout.write("\b"*4)
<numbers count here>
>>>
网友答案:

A trailing comma suppresses the newline, a carriage return moves to the beginning of the line.

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

This works on Linux.

网友答案:

you can try this :

import sys
import time
for num in range(100):
    sys.stdout.write("\r "+str(num))
    sys.stdout.flush()
    time.sleep(0.3)
网友答案:

It looks to me like you are looking for a progress bar. If so check out some ready-made ones.

Even if you are not making a progress bar, the code therein would need to do something similar. Perhaps it can give you some clues.

As I am not a python guy, I don't know the python syntax. For Perl you can add a \r character to an interpolated quotation, this moves the cursor back to the beginning of the line, thus overwriting any previous text on the next iteration. Perhaps python has a similar character.

perl -e 'print "$_\r" for (1..100); print "\n";'
网友答案:

Depends on your platform. If the curses module is available to you, use that. If you're on Windows, and using a sufficiently old version of Python (2.6 and earlier), you could try Fredrik Lundh's Console.

网友答案:

Simplest way is to use the backspace character \b like

from __future__ import print_function
import sys, time

for i in range(1, 100):
  print('\b\b\b%d' % i, end='')
  sys.stdout.flush()
  time.sleep(0.1)
分享给朋友:
您可能感兴趣的文章:
随机阅读: