P'sao
P'sao

Reputation: 2996

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.

Upvotes: 0

Views: 4450

Answers (6)

Yuda Prawira
Yuda Prawira

Reputation: 12461

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)

Upvotes: 1

Reci
Reci

Reputation: 4274

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)

Upvotes: 0

John Y
John Y

Reputation: 14519

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.

Upvotes: 0

tMC
tMC

Reputation: 19315

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

Upvotes: 3

Keith
Keith

Reputation: 43024

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.

Upvotes: 3

Joel Berger
Joel Berger

Reputation: 20280

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";'

Upvotes: 0

Related Questions