0

Following python script

import time

numbers = [11111, 2222, 333, 44, 5]
for number in numbers:
  print("{}".format(number), end='\r', flush=True)
  time.sleep(1)
print()

outputs 54321, which is supposed to be 5, how can I erase previous line on screen without any residues? Thanks!

mzoz
  • 1,273
  • 1
  • 14
  • 28
  • You have one less number each time, so you overwrite only one less at each iteration – azro Aug 15 '20 at 16:40
  • Hi @azro, I deliberately wrote in this way to demonstrate the problem, it seems the print statement just obeys `end` attribute not `flush` – mzoz Aug 15 '20 at 16:43
  • Several of the answers to https://stackoverflow.com/questions/5419389/how-to-overwrite-the-previous-print-to-stdout-in-python explain how to overwrite the previous line with blanks before writing the new characters. – Craig Aug 15 '20 at 16:46
  • the `flush` means : go and show it NOW, just that, it doesn't erase anything – azro Aug 15 '20 at 16:49
  • Hi @Craig, still the same, as long as previous line has more characters than current line they're left there on screen – mzoz Aug 15 '20 at 16:50
  • @azro do you know any method that can erase the previous line on screen... thanks! – mzoz Aug 15 '20 at 16:51
  • You need to keep track of how many characters are in the previous line, as is shown in this answer: https://stackoverflow.com/a/43952192/7517724, Or, if you know the max length of your lines, just write that many " " characters. – Craig Aug 15 '20 at 17:09

1 Answers1

0

To erase the current line use '\x1b[2K'
Try this:

import time

numbers = [11111, 2222, 333, 44, 5]
for number in numbers:
  print('\x1b[2K', end='\r')
  print("{}".format(number), end='\r')
  time.sleep(1)

Reference: Adapted the answer at https://stackoverflow.com/a/25105111/14066252

PiyushC
  • 308
  • 1
  • 9