Delete last printed character python
Solution 1
When using print
in python a line feed (aka '\n'
) is added. You should use sys.stdout.write()
instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
Solution 2
You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer
Ofer Arial
Apparently, users tend to prefer to keep an air of mystery about them.
Updated on June 18, 2022Comments
-
Ofer Arial about 2 years
I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen", print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as:
\010
,'\033[#D'
(# is 1),'\r'
).These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using
sys.stdout.write
doesn't change the affect. It just doesn't erase the last printed character. Instead, when usingsys.stdout.write
, my output is:Ofenr # with a square before 'r'
My questions:
- Why don't these options work?
- How do I achieve the desired output?
- Is this related to Windows OS or Python 2.7?
- When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the
'\n'
that is printed in python'sprint
statement?