Deleting already printed in Python - python

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

Related

Way to change already printed string

Yesterday I coded a Hangman game. I got it finished and it works but now im asking myself "could it be better"?
I thought of a line of underscores to let the user know how many digits there are and than a way to chose. If the chosen letter is in the word that needs to be guessed it replaces the underscore with the letter.
This is my try
I dont know how to change the printed string or refresh the choice option.
Thx for any answer.
You can add end='\r' to the line which should be overwritten.
For the last line you should use the default end switch, otherwise the line is overwritten in the terminal (at least on linux).
import time
print('This is line 1', end='\r')
time.sleep(1)
print('This is line 2')

Stop python command interpreter from echoing

In Linux, python3, I paste this code at the >>> python command-line...
my_string = "Blackpool rock is magic"
string_split = my_string.split() # creates a list.
# Elements of which are each
# word in the string.
print(f"len of string = {len(my_string)}")
for t in range(len(string_split)):
print(f"string_split[{t}] = {string_split[t]}")
print(f"string_split = {string_split}")
Inbetween the pasted code, I see some output inbetween some coded lines
e.g.
How can I get all my print statement to appear at the end of the code and not be interspersed with the code (even though I can see it being useful for debugging)? - Is there an "code echo off" like feature?
Am I right in thinking after a For loop you need to have a blank line?
When pasting code sometime I need to press enter a couple of time to complete the code. Is there an escape character or something to ensure the program terminates without needing to press enter 1 or two times?

What does this mean in Python '\x1b[2K'?

I've just learnt that to clear a line that you printed in Python, do this:
sys.stdout.write('\x1b[2K')
Why is it so complicated? what does that weird code mean? and is there any alternative in print command?
Print does offer "end" option that allows to go back and forth in lines, but no way to clear what you printed. Overwriting via \r doesn't always work especially if the new line is shorter than the old one. You will get traces from the old line, so I need clearing first.
Thanks.
\x1b[2K is what's known as an ANSI terminal control sequence. They are a legacy of the 1970s and still used today (but vastly extended) to control terminal emulators.
\x1b is the ASCII for ESCAPE (literally the ESC key on your keyboard). [2K is the command "erase the current line".
There are many libraries in Python for working with the terminal, such as Urwid. These libraries will hide the inner workings of the terminal from you and give you higher-level constructs to create TUIs.
However, there is a much more efficient way of doing this:
You can use the print() command as usual, and delete the screen using
os.system("cls") # For Windows
or
os.system("clear") # For Linux
Alternative to print on a single line
I have a script that prints the x, y coordinates of the mouse as such:
import pyautogui
import time
while True:
x, y = pyautogui.position()
position_string = "X: {} Y: {}".format(str(x).rjust(4), str(y).rjust(4))
print(position_string, end='')
print('\b' * len(position_string), end='', flush=True)
time.sleep(1)
Where I will point out that you can print the backspace character ('\b') the amount of times that there are characters on the screen (len(position_string)), and when used with the end='' and flush=True options this will constantly print on a single line within your console. I should also note that this does not work in IDLE, but only on an actual command line! In IDLE the backspace characters are actually printed as some weird square shape...
This is called ANSI escape code . 2K is the name for Erase in Line. Quote from the link:
Erases part of the line. If n is 0 (or missing), clear from cursor to the end of the line. If n is 1, clear from cursor to beginning of the line. If n is 2, clear entire line. Cursor position does not change.
You can also try echo -e '\x1b[2k' in the terminal for better understanding.

Replacing more than one line in the console in python

I'm writing a program in python and I'd like to replace more than one line in the console with new text.
For example if I have 3 sentences printed to the console with:
print("Hello World!")
print("How are you!")
print("What's going on?")
Where each on is on a different line (and so has an \n).
How do I go about replacing all of this text when it displays in the console? I can't us \r in this situation due to the \n.
This is kind of an old post, but I came across it and worked out a solution as well. Added a timer, because otherwise the print statements bury each other and you'll only be able to read the last one. I'm on python 2.7:
import os
import time
os.system("printf 'Hello World!'")
time.sleep(1)
os.system("printf '\rHow are you?!'")
time.sleep(1.5)
os.system("printf '\rWhats going on?'")
os.system("echo ")
A simple fix would be to simply change the end separator for printing your strings. you can specify how you want the print function to separate calls with the end argument
print("hello world!", end="")
print("\rhello world again!")
In this case, we're setting the separator to "", which is nothing. So printing the next strings starts on the same line thus \r can be used. Compiling that gives you hello world again! on one line.

Python (and possibly others) - What is the escape character for a space?

Pretty simple concept, but I can't figure it out and could use some help. I need to check if a file in my Program Files directory exists, so I have the following:
import os
if not os.path.exists('C:/Program Files/file_to_be_found'):
print "ERROR: Not Found!"
else:
#rest of program...
However I know I can't do it this way. How can I write the path in the command to accept the space between "Program" and "Files"?
the space is ok. and you are free to write the slash.
if os.path.exists('C:/Program Files'): print 'yes'
if os.path.exists(r'C:\Program Files'): print 'yes'
if os.path.exists('C:\\Program Files'): print 'yes'
all above are ok with or without a "r".
#nneonneo reminded that the second one is dangerous without "r" because the backslash is used to escape.

Categories