How to print new values without making a new line? (timer)

Viewed 179

I am making a timer and it works great. The only problem is that every time a second passes, it prints the time left in seconds in a new line. How do I make it so that instead of printing a new line it just changes what is displayed in the current line?

This is what I have...

import time

t = int(input("Time (in seconds): "))

while t > 0:
    time.sleep(1)
    t -= 1
    print(t)

print("TIME DONE")
1 Answers

By default print() prints newline after the given string. You can use end='..' to specify another character instead of newline.

Note that standard output is line buffered. Not printing newline will make the output buffered. You can force it displayed by calling sys.stdout.flush() or specify flush=True (Python 3.3+)

print(t, end='')
sys.stdout.flush()

# OR

print(t, end='', flush=True)

If you want printed text replaced, you can use carriage return (\r),

print('\r', t, end='')
# OR
print('\r', t, sep='', end='')  # if you keep leading space printed.
Related