简体   繁体   English

删除 Python 打印行中的字符

[英]Delete Characters in Python Printed Line

I'm writing a program where I want the cursor to print letters on the same line, but then delete them as well, as if a person was typing, made a mistake, deleted back to the mistake, and kept typing from there.我正在编写一个程序,我希望光标在同一行上打印字母,但随后也将它们删除,就好像有人在打字,犯了一个错误,删除回错误,然后继续从那里打字。

All I have so far is the ability to write them on the same line:到目前为止,我所拥有的只是将它们写在同一行上的能力:

import sys, time
write = sys.stdout.write

for c in text:  
    write(c)
    time.sleep(.5)
write('\b')  # <-- backup 1-character

Just to illustrate the great answers given by @user590028 and @Kimvais只是为了说明@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")

References参考
[1] This answer by Sven Marnachin in Python Remove and Replace Printed Items [1] Sven Marnachin 在 Python Remove and Replace Printed Items 中的这个答案
[2] Blog post about building progress bars [2] 关于构建进度条的博客文章

当您使用print() ,您可以将 end 设置为\\r ,它将用新文本替换该行中的文本。

print(text, end="\r")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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