删除Python打印行中的字符

JSh*_*hoe 9 python

我正在编写一个程序,我希望光标在同一行上打印字母,然后删除它们,好像一个人正在打字,犯了错误,删回了错误,并从那里继续打字.

到目前为止,我所有人都能够在同一条线上写下它们:

import sys, time
write = sys.stdout.write

for c in text:  
    write(c)
    time.sleep(.5)
Run Code Online (Sandbox Code Playgroud)

use*_*028 19

write('\b')  # <-- backup 1-character
Run Code Online (Sandbox Code Playgroud)

  • +1,你可能想写'('\ b\b')`以获得所需的效果. (4认同)

Tai*_*Tai 5

只是为了说明@ 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")
Run Code Online (Sandbox Code Playgroud)

参考文献
[1] Sven Marnachin在Python中的回答删除和替换印刷项目
[2]关于构建进度条的博客文章


RCR*_*lph 5

使用时print(),可以将 end 设置为\r,这会将行中的文本替换为新文本。

print(text, end="\r")
Run Code Online (Sandbox Code Playgroud)