Reputation: 79
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?
Upvotes: 1
Views: 1004
Reputation: 79
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
Upvotes: 1
Reputation: 191
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')
Upvotes: 0