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 using sys.stdout.write
, my output is:
Ofenr # with a square before 'r'
My questions:
'\n'
that is printed in python's print
statement?Then for removing the last character of the string, the indexing always starts from -1. By slicing it from the -1 index, we have removed the last character of the string. At last, we have printed the output. Hence, we have seen that the unwanted character has been removed. 3. Using the rstrip function to Remove Last Character From String in Python
Explanation: Removing the last 5 characters from “GeeksForGeeks” modifies the string to “GeeksFor”. Initialize an empty string, say res, to store the resultant string. Iterate over the characters of the string S up to index len(S) – N.
This slicing technique can be used to cut out a piece of string that includes all characters except the last N characters. To delete the last N characters from a string, we can iterate through the string’s characters one by one, selecting all characters from index position 0 until the size – n of the string.
When using print in python a line feed (aka ' ') is added. You should use sys.stdout.write () instead. Show activity on this post. 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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With