[英]Delete last printed character python
I am writing a program in Python and want to replace the last character printed in the terminal with another character.我正在用 Python 编写程序,想用另一个字符替换终端中打印的最后一个字符。
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.我使用的是 Windows8 操作系统、Python 2.7 和常规解释器。
All of the options I saw so far didn't work for me.到目前为止我看到的所有选项都不适合我。 (such as:
\\010
, '\\033[#D'
(# is 1), '\\r'
). (例如:
\\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.这些选项是在其他 Stack Overflow 问题或其他资源中建议的,似乎对我不起作用。
EDIT : also using sys.stdout.write
doesn't change the affect.编辑:也使用
sys.stdout.write
不会改变影响。 It just doesn't erase the last printed character.它只是不会擦除最后一个打印的字符。 Instead, when using
sys.stdout.write
, my output is:相反,当使用
sys.stdout.write
,我的输出是:
Ofenr # with a square before 'r'
My questions:我的问题:
'\\n'
that is printed in python's print
statement?print
语句中打印的'\\n'
?When using print
in python a line feed (aka '\\n'
) is added.在 python 中使用
print
,会添加换行符(又名'\\n'
)。 You should use sys.stdout.write()
instead.您应该改用
sys.stdout.write()
。
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
输出:
Ofer
You can also import the print function from Python 3. The optional end argument can be any string that will be added.您还可以从 Python 3 导入打印函数。可选的 end 参数可以是将要添加的任何字符串。 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
I think string stripping would help you.我认为字符串剥离会帮助你。 Save the input and just print the string upto the
length of string -1
.保存输入并将字符串打印到
length of string -1
的length of string -1
。
Instance实例
x = "Ofen"
print (x[:-1] + "r")
would give you the result会给你结果
Ofer
Hope this helps.希望这可以帮助。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.