4

How to replace printed statements in Python 2.7, for example:

for i in range(100):
    print i,"% Completed"

#Result Must Be:
>>> 1 % Completed 

The 1 must be replaced by 2 and so on. But not in different line or append on same line.

I tried searching about it, found solution such as

from __future__ import print_function
print("i: "+str(i),end="\r")

But they result in appended print statements. Is there any correction in my print_function or is there a different solution?

Craziest Hacker
  • 99
  • 3
  • 11

2 Answers2

4

Do you want something like this:

>>> import sys, time
>>> for i in range(100):
...     time.sleep(0.1)
...     sys.stdout.write('%d %% Completed \r' % (i,))
...     sys.stdout.flush()
Rohit Jain
  • 203,151
  • 43
  • 392
  • 509
2

Here you go:

from __future__ import print_function

for i in range(100):
    print('{0}% Completed\r'.format(i), end='')
print('100% Completed')

Set a higher range if you actually want to see it work for a few seconds.

timgeb
  • 73,231
  • 20
  • 109
  • 138