简体   繁体   English

删除最后打印的字符python

[英]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:我的问题:

  1. Why don't these options work?为什么这些选项不起作用?
  2. How do I achieve the desired output?我如何实现所需的输出?
  3. Is this related to Windows OS or Python 2.7?这是否与 Windows 操作系统或 Python 2.7 有关?
  4. 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's print statement?当我找到如何做时,是否可以手动擦除(使用想要的橡皮擦),删除在 python 的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 -1length 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM