0

I'm trying to make a progress meter that counts up until 100%, but I can't make it replace the line, instead it prints out: 0% 1% 2%

So how could I make it change using only one line?

This is my code:

x = range(101)
for n in x:
    timefluc = random.uniform(0, 1.2)
    time.sleep(timefluc)
    print("{0}%".format(n))

2 Answers2

2

By default, print adds a newline, '\n', after all arguments have been printed, moving you to the next line. Pass it end='\r' (carriage return) to make it return to the beginning of the current line without advancing to the next line. To be sure output isn't buffered (stdout is typically line buffered when connected to a terminal), make sure to pass flush=True to print as well, for a final result of:

for n in range(101):
    timefluc = random.uniform(0, 1.2)
    time.sleep(timefluc)
    print("{0}%".format(n), end='\r', flush=True)
ShadowRanger
  • 124,179
  • 11
  • 158
  • 228
0

That would depend on your terminal / console application, and there is no truly standard way, but you can try printing 'carriage return' character to go to beginning of the line:

x = range(101)
for n in x:
    timefluc = random.uniform(0, 1.2)
    time.sleep(timefluc)
    print("\r{0}%".format(n), end='')

Note the \r and also the usage of end='' argument.
\r is the "carriage return" that should return to beginning of line, and the end argument prevents print from going to the next line after printing the percentage.

Also you may want to use {0:3} for formatting which will keep the filed 3 characters long, automatically adding spaces on the left for padding, so that the percentage won't jump around as you go from 1% to 10% to 100%.

Lev M.
  • 5,674
  • 1
  • 8
  • 22