[Python] How do I erase the last word printed onto the terminal?

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to be able to erase the last word printed onto the terminal. The last word should be the last string of text following a space. The following code simulates what I am trying to achieve. I want a function remove_last_word() that will erase str.

    import random

    words = ['apple', 'banana', 'cherry', 'dog', 'elephant', 'flower', 'guitar', 'house', 'island', 'jungle']
    str = 'stop.\n'

    for i in range(0, random.randint(0, 100)):
    print(random.choice(words), end=' ')
    print(str, end='')

    remove_last_word()


    Simply printing a carriage return won't work because there might be a newline at the end of the word. Moving the cursor up a line and printing a carriage return won't work because that will overwrite the previous words printed onto the terminal. I need a way to access the contents of the terminal so that I can find the start of the the last word.

    Continue reading...

Compartilhe esta Página