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)
Note that \r
does not erase the line, so this only works because in your code, each new output is guaranteed to be at least as long as the previous line (and therefore will overwrite the entirety of the last line's data). If you might output a long line, then a short line, you'll need to make sure to pad all outputs with spaces sufficient to match or exceed the length of the longest possible line (without exceeding the terminal width).