1

I am trying to write a time algorithm. However, I am having a problem successfully printing the code on the same line by overwriting the previous print

I have tried to use "\r" to print it on the same line. However, it does not work as after finishing the first minute, the seconds go like 09,19,29,39 and so on.. not sure what the problem is here.

However, if I remove the "\r", the program works fine except it prints the time in a new line every time. I want to print it in the same line.

import time
for i in range(24):
    for a in range(60):
        for s in range(60):
            print(i,":",a,":",s, end='\r')
            time.sleep(1)

I expect the output to be a just like normal time. However it isn't working the same way not sure why

danblack
  • 12,130
  • 2
  • 22
  • 41

1 Answers1

1

The 9 character that follows 0, 1, 2, etc. after the first minute is simply the 9 in the 59 that was printed in the last second of the first minute, since the single-digit seconds do not have enough width to overwrite the 9. You can format the output of each number with a width of 2, and since we're dealing with time here, pad the numbers with leading 0:

import time
for i in range(24):
    for a in range(60):
        for s in range(60):
            print('%02d:%02d:%02d' % (i, a, s), end='\r')
            time.sleep(1)

If you run this in IDE, it will not output anything because the output is buffered until a newline character is received. You can force-flush the output with the flush=True argument, but then the IDE will still not output anything because the \r character erases the output due to the IDE's pre-processing. You can instead flush the output first before printing \r:

import time
for i in range(24):
    for a in range(60):
        for s in range(60):
            print('%02d:%02d:%02d' % (i, a, s), end='', flush=True)
            time.sleep(1)
            print('', end='\r')
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • I have just recently started using visual studio code as my editor and turns out this works fine in the terminal but just wanted to ask why doesn't it work when running in idle? – Mayank agrawal Apr 04 '19 at 17:16
  • In IDE, the output is buffered and the IDE would only actually output the buffer to the screen when there is a newline character, and there is no newline character output from this code. – blhsing Apr 04 '19 at 17:19
  • I tried to run the new solution and the old solution on IDLE, but it still results in the output time printed side by side – Mayank agrawal Apr 04 '19 at 17:29
  • Python's IDLE does not support moving the cursor to the beginning of a line using the `\r` character at all, so it is simply not possible with IDLE. Please simply use a different IDE. – blhsing Apr 04 '19 at 17:36