1

I am trying to overwrite the previously printed terminal line with a shorter print than before. I had a look at the article Remove and Replace Printed items and tried to figure out how to make it work for a shorter print, but the given tips are just working if the previous line is shorter than the text of the new print. Meaning:

print('Test', end='\r')
print('TestTest')

prints Test first and then TestTest into the same line but

print('Tessst', end='\r')
print('Test')

prints Tessst first and then Testst where it keeps the last two characters of the first print. I also tried to use sys.stdout.flush() (which apparently is for older Python versions) and the print option flush=True but neither of them worked. Is there another approach to make it work?

lasbr
  • 53
  • 6

2 Answers2

1

I have found a decent work around for this problem. You can just fill the end of the string with white spaces with f strings. The full code for the problem I stated in the question would then be:

print('Tessst', end='\r')
print(f'{"Test" : <10}')

I found this way here

lasbr
  • 53
  • 6
0

flush() just means that all the printed data should be written to the output stream. It doesn't relate to what you're trying to do.

If you want to overwrite the current line, you can put space characters after your second print to blank out the character cells on the screen. Or, if you have a fancy terminal like Xterm or a VT emulator, there is an escape sequence which will cause the rest of the line to be deleted:

print('Tessst', end='\r')
print('Test\033[K')
RGoodman
  • 81
  • 6
  • I forgot to mention that I also tried this approach, but for me it just keeps printing a fancy square with a questionmark followed by `[80P` as it seems to not be recognizing `\033[80P` – lasbr May 13 '20 at 15:53
  • 1
    Then you might just add spaces to the end of the second print() to cover up the rest of the line. – RGoodman May 13 '20 at 16:32
  • That works, thanks, but it's not a really good looking way :D – lasbr May 13 '20 at 22:02