我正在编写一个程序,我希望光标在同一行上打印字母,然后删除它们,好像一个人正在打字,犯了错误,删回了错误,并继续打字那里。
到目前为止,我所有人都能够在同一条线上写下它们:
import sys, time
write = sys.stdout.write
for c in text:
write(c)
time.sleep(.5)
答案 0 :(得分:18)
write('\b') # <-- backup 1-character
答案 1 :(得分: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")
<强>参考强>
[1] This answer by Sven Marnachin in Python Remove and Replace Printed Items
[2] Blog post about building progress bars
答案 2 :(得分:0)
使用print()时,可以将end设置为\ r,它将用新文本替换行中的文本。
print(text, end="\r")