Is there a way how to replace an input text/letter with printed statement in python? I've tried the("", end"r") but it doesn't work.
I'd like the y/Y which users type in to be replaced with YES and the same with n/N - replaced with NO.
user_choice = input("Are you ready to play? (Y/N)\n---\n").upper()
while user_choice:
if user_choice == "Y":
print("YES", end="\r")
get_random_word()
break
elif user_choice == "N":
print('NO', end="\r")
CodePudding user response:
You can do this by taking the cursor up one line up (where Y or N was typed) and then deleting the line. Then replacing it with YES or No
This can be done by using a function, shown in the code below.
import sys
def delete_last_line():
"Use this function to delete the last line in the STDOUT"
#cursor up one line
sys.stdout.write('\x1b[1A')
#delete last line
sys.stdout.write('\x1b[2K')
user_choice = input("Are you ready to play? (Y/N)\n---\n").upper()
while user_choice:
if user_choice == "Y":
delete_last_line()
print("YES")
get_random_word()
break
elif user_choice == "N":
delete_last_line()
print('NO')