Search code examples
pythonloopsprintingline

Is it possible to print a constantly updating variable on one line?


This is just a simple example,

import time
for i in range (1,11):
    print(i)
    time.sleep(1)

This code counts to 10, but each printed i value is on a new line. Is it possible to print them all on the first line, and with each new print, delete that current number, so it counts to 10 in one place?


Solution

  • You may use sys.stdout.write.

    import sys
    import time
    for i in range (1,11):
        sys.stdout.write('\r' + str(i))
        sys.stdout.flush()
        time.sleep(1)