开发者

Deleting already printed in Python

开发者 https://www.devze.com 2023-01-05 04:58 出处:网络
For practice, I\'m trying to do some stuff in Python. I\'ve decided to make a simple hangman game - I\'m not making a GUI. The game would start 开发者_开发技巧with a simple input(). Now, I\'d like nex

For practice, I'm trying to do some stuff in Python. I've decided to make a simple hangman game - I'm not making a GUI. The game would start 开发者_开发技巧with a simple input(). Now, I'd like next line to, beside asking for input, to delete the hidden word. I've tried using \b (backspace character), but it's not working. Something like:

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

Now, printing the backlash character is supposed to delete the input and "Your word", but it isn't doing anything. If I do this in IDLE I get squares, and I get nothing if I open it by clicking.

How to accomplish this? I'm afraid I wasn't too clear with my question, but I hope you'll see what I meant. :)


\b does not erase the character before the cursor, it simply moves the cursor left one column. If you want text entry without echoing the characters then look at getpass.


I assume the player entering the word wants to be sure they've entered it correctly so you probably want to display the word as they're typing it right?

How about printing enough \ns to move it off the screen when they're done or issue a clear screen command?

You mentioned this was a simple game so a simple solution seems fitting.

[Edit] Here's a simple routine to clear the console on just about 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


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

This will replace the last line printed with 25 spaces.


I think part of your problem is that input is echoing the Enter that terminates your word entry. Your backspaces are on another line, and I don't think they'll back up to the previous line. I seem to recall a SO question about how to prevent that, but I can't find it just now.

Also, I believe print, by default, will output a newline on each call, so each backspace would be on its own line. You can change this by using an end='' argument.

Edit: I found the question I was thinking of, but it doesn't look like there's any help there. You can look at it if you like: Python input that ends without showing a newline

0

精彩评论

暂无评论...
验证码 换一张
取 消