[Python] how to delete or clear printed text in python

Discussão em 'Python' iniciado por Stack, Dezembro 19, 2024.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página