Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete the last input row in Python

I have the following code:

num = int(raw_input("input number: "))
print "\b" * 20

The console output looks like

input number: 10

I'd like to delete the text input number: 10 after the user presses ENTER. The backspace key \b can't do it.

like image 576
xralf Avatar asked May 31 '12 08:05

xralf


People also ask

How do you clear inputs in Python?

The clear() method removes all elements in a set.

How do you delete a print line in Python?

In python2. x you can add a comma (,) at the end of the print statement that will remove newline from print Python.

How do you delete old text in Python?

In Python you can use the replace() and translate() methods to specify which characters you want to remove from a string and return a new modified string result. It is important to remember that the original string will not be altered because strings are immutable.


3 Answers

This will work in most unix and windows terminals ... it uses very simple ANSI escape.

num = int(raw_input("input number: "))
print "\033[A                             \033[A"    # ansi escape arrow up then overwrite the line

Please note that on Windows you may need to enable the ANSI support using the following http://www.windowsnetworking.com/kbase/windowstips/windows2000/usertips/miscellaneous/commandinterpreteransisupport.html

"\033[A" string is interpreted by terminal as move the cursor one line up.

like image 104
Maria Zverina Avatar answered Oct 01 '22 02:10

Maria Zverina


There are control sequences for 'word back' and 'line back' and the like that move the cursor. So, you could try moving the curser back to the start of the text you want to delete, and overriding it with spaces. But this gets complicated very quickly. Thankfully, Python has the standard curses module for "advanced terminal handling".

The only issue with this is that it isn't cross-platform at the moment - that module has never been ported to Windows. So, if you need to support Windows, take a look at the Console module.

like image 38
lvc Avatar answered Oct 01 '22 01:10

lvc


import sys

print "Welcome to a humble little screen control demo program"
print ""

# Clear the screen
#screen_code = "\033[2J";
#sys.stdout.write( screen_code )

# Go up to the previous line and then
# clear to the end of line
screen_code = "\033[1A[\033[2K"
sys.stdout.write( screen_code )
a = raw_input( "What a: " )
a = a.strip()
sys.stdout.write( screen_code )
b = raw_input( "What b: " )
b = b.strip()
print "a=[" , a , "]"
print "b=[" , b , "]"
like image 26
RJ Mical Avatar answered Oct 01 '22 00:10

RJ Mical