-1

I'm writing a simple game. The user is given information about a crime and has to guess who the culprit is. I have long pieces of information:

"This is the story of Catherine Claythorne. When she was in college, she was a beauty and her best friend, William Claythorne, an IT genius fell in love with her. However, she decided to married William's brother, Edward Claythorne. After college Edward and his best friend, Lawrence Wargrave, started working for MacArthur Corp and they have been climbing the corporate ladder ever since."

I created a function to separate the pieces of information into sentences and to print sentence by sentence while waiting for the user to confirm that he has finished reading the text:

def print_waiting_for_user(txt):
    by_periods = txt.split(". ")
    for line in by_periods:
        sys.stdout.write(line + "(PRESS C to continue)")
        waiting = input()
        sys.stdout.flush()

I want my function to erase all previous output before printing the next.

As you can see in the previous code sample, I've tried using sys.stdout. I've also tried using print(line, end = '\r'):

def print_waiting_for_user(txt):
    by_periods = txt.split(". ")
    for line in by_periods:
        print(line, "(Press C to continue)", end='\r')
        waiting = input()

I've also tried using flush = True:

def print_waiting_for_user(txt):
    by_periods = txt.split(". ")
    for line in by_periods:
        print(line, "(Press C to continue)", flush=True)
        waiting = input()

Nothing seems to work for me, can you help me? please thanks in advance

1 Answers1

0

This can be a bit tricky, because it depends on the terminal.

You can print a bunch of '\b' (backspace) characters, then print your next string, but you also need to print enough letters to ensure you erase the old string too. So add enough spaces to clear it.

e.g.:

sentence1 = "the cat sat on the mat"
sentence2 = "the dog too"

print(sentence1, end='')
print("\b" * len(sentence1), end='')
print(sentence2, end='')
if (len(sentence2) < len(sentence1)):
    print(" " * (len(sentence1) - len(sentence2))) 

Maybe a function would be better

def printAndHome(sentence, eraser):
    print(sentence1, end='')
    print(" " * eraser, end='')
    print("\b" * len(sentence1), end='')
    return len(sentence)

It's possibly too complex for simply erasing the line, but if you really want to get into this sort of stuff, it may be worth investigating the python interface to the "curses" library.

Kingsley
  • 14,398
  • 5
  • 31
  • 53