I want to write a program using Python in which looks something like this-
text = input("Enter an integer:")
But as soon as the user enters an integer and clicks Enter, the entire line gets deleted. Then, I would like to add another line in it's place.
I know about \r
, and how it can be used to get to the beginning of a line, but am not sure how to proceed from there onwards. I also don't want the input to be written over the line, Enter an integer
in this case.
I'm using a MacOS Terminal with a zsh shell.
One workaround would be to follow your input()
with a print()
statement that begins with the special character \0331A
which returns to the start of the previous line in the console, followed by \033[K
which erases the line until its end. Then you can proceed with any other printing you want to do:
text = input("Enter an integer:")
print('\033[1A', '\033[K', end='')
print('Some new text')
To explain what is happening, we are using ANSI escape codes to control the console. The special character \033
(ESC
) takes parameters as documented here. We are using it twice:
\033[1A
- the parameter is 1A
. The A
means to move the cursor up some number of rows, and 1
is that number.\033[K
- the parameter is K
. This command erases from the cursor position to the end of the row.