Search code examples
pythonprintingterminallineoverwrite

Python 3.8: Overwrite and clear previous shorter line in terminal


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?


Solution

  • 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