Ofe*_*ial 5 python printing python-2.7
我正在用 Python 编写程序,想用另一个字符替换终端中打印的最后一个字符。
伪代码为:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
Run Code Online (Sandbox Code Playgroud)
我使用的是 Windows8 操作系统、Python 2.7 和常规解释器。
到目前为止我看到的所有选项都不适合我。(例如:\010,'\033[#D'(# 为 1),'\r')。
这些选项是在其他 Stack Overflow 问题或其他资源中建议的,似乎对我不起作用。
编辑:也使用sys.stdout.write不会改变影响。它只是不会擦除最后一个打印的字符。相反,在使用时sys.stdout.write,我的输出是:
Ofenr # with a square before 'r'
Run Code Online (Sandbox Code Playgroud)
我的问题:
'\n'在 pythonprint语句中打印的?print在 python 中使用时,'\n'会添加换行符(又名)。你应该sys.stdout.write()改用。
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
输出: Ofer
小智 5
您还可以从 Python 3 导入 print 函数。可选的 end 参数可以是要添加的任何字符串。在你的情况下它只是一个空字符串。
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")
Run Code Online (Sandbox Code Playgroud)
输出
Ofer
Run Code Online (Sandbox Code Playgroud)