Uninstall already printed in Python

For practice, I'm trying to do something in Python. I decided to make a simple hangman game - I am not creating a graphical interface. The game starts with a simple input (). Now, I would like the next line, in addition to the input request, to delete the hidden word. I tried using \ b (backspace character) but it does not work. Something like:

word = input("Your word: ") for i in range(len(word) + 12): print("\b") 

Now printing the backlash symbol should remove the input and "Your word", but it does nothing. If I do this in IDLE, I get the squares and get nothing if I open it by clicking.

How to do it? I'm afraid I was not too clear with my question, but I hope you understand what I mean. :)

+4
python printing
source share
4 answers

I assume that the player entering the word wants to be sure that he entered it correctly, so you probably want to display that word when it prints it correctly?

How to seal \n enough to move it off the screen when they are done, or issue a clear screen command?

You mentioned that it was a simple game, so a simple solution seems appropriate.

[Change] Here is a simple procedure for cleaning the console on almost any platform (taken from here ):

 def clearscreen(numlines=100): """Clear the console. numlines is an optional argument used only as a fall-back. """ import os if os.name == "posix": # Unix/Linux/MacOS/BSD/etc os.system('clear') elif os.name in ("nt", "dos", "ce"): # DOS/Windows os.system('CLS') else: # Fallback for other operating systems. print '\n' * numlines 
+2
source share

\b does not erase the character before the cursor, it just moves the cursor left one column. If you want to enter text without repeating characters, see getpass .

+4
source share
 word = raw_input("Your word: ") import sys sys.stdout.write("\x1b[1A" + 25*" " + "\n") 

This will replace the last line printed with 25 spaces.

+3
source share

I think part of your problem is that input echoes Enter, which completes the writing of your word. Your backspaces are on a different line, and I don't think they will go back to the previous line. I seem to recall the SO question on how to prevent this, but I cannot find it now.

In addition, I believe that print prints a new line for each call by default, so each backspace will be on a separate line. You can change this using the argument end='' .

Edit: I found a question that I was thinking about, but there seems to be no help there. You can look at it if you want: Python input that ends without displaying a new line

+1
source share

All Articles