Search code examples
pythonpython-3.xjupyterjupyter-lab

how to delete or clear printed text in python


I'm learning python in Jupyterlab. Currently, I tried to find a way to clear the printed text in Jupyterlab but I haven't gotten any luck.

I searched online to find a few solutions. However, they won't clear the printed text in my console even though others have reported position results.

I tried the (1). '\b' character (2)os.system('cls') (3)sys.stdout.write

all of them failed to clear the printed text.

print('Hello',end='')
print(5*'\b')
print('how are you?',end='')

output: Hell how are you?

print('Hello',end='')
for i in range(len('Hello')):
    print('\b',end='')

print('how are you?',end='')

output: Hellhow are you?

print('Hey')
import os
if os.name=='nt':
    os.system('cls')
else:
    os.system('clear')
print('how are you?')

output: Hey how are you?

import sys, time

def delete_last_line():
    sys.stdout.write('\x1b[1A')
    sys.stdout.write('\x1b[2K')

print("hello")
time.sleep(2)
delete_last_line()
print("how are you")

output: hello how are you

I wonder if it's because the system or modules have updated so that the methods no longer work the same way or my computer or Jupyterlab has bugs causing the failure.


Solution

  • Be careful of the length, \r the cursor returns to the beginning of the line, but it is not overwritten, it is overwritten only from the beginning with the entered text.

    print('Hello', end='\r')
    # >>> Hello
    print('How are you?', end='\r')
    # >>> How are you?
    print('TEST', end='\r')
    # >>> TESTare you?
    

    Maybe I would suggest an auxiliary function:

    def echo(string, padding=80):
        padding = " " * (padding - len(string)) if padding else ""
        print(string + padding, end='\r')
    
    echo("Hello")
    # >>> Hello
    echo("How are you?")
    # >>> How are you?
    echo("TEST")
    # >>> TEST