在Python打印行中删除字符
问题描述:
我正在编写一个程序,我希望光标在同一行上打印字母,但也要删除它们,就好像一个人正在输入,犯了一个错误,将其删除回到错误,并从那里继续打字。在Python打印行中删除字符
所有我至今是他们写在同一行的能力:
import sys, time
write = sys.stdout.write
for c in text:
write(c)
time.sleep(.5)
答
write('\b') # <-- backup 1-character
+3
+1,你可能想'写('\ b \ b')'来达到理想的效果。 – Kimvais 2012-03-31 05:58:11
答
只是为了说明通过@ user590028和@Kimvais
sys.stdout.write('\b') # move back the cursor
sys.stdout.write(' ') # write an empty space to override the
# previous written character.
sys.stdout.write('\b') # move back the cursor again.
# Combining all 3 in one shot:
sys.stdout.write('\b \b')
# In case you want to move cursor one line up. See [1] for more reference.
sys.stdout.write("\033[F")
给伟大的答案参考文献
[1] This answer by Sven Marnachin in Python Remove and Replace Printed Items
[2] Blog post about building progress bars
您可以通过将其缩进四个空格(或者粘贴并选择它,然后单击代码按钮)来很好地格式化代码。 – 2012-03-30 20:21:57
您可能想要查看unix的[curses](http://docs.python.org/library/curses.html)软件包或windows的替代软件。我使用的是[msvcrt](http://docs.python.org/library/msvcrt.html)。如果你只是试图在控制台中伪造用户,那么'\ b'字符将起作用。 – jgritty 2012-03-30 20:20:49