删除Python打印Lin中的字符

2024-04-23 23:26:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,我希望光标在同一行上打印字母,但随后也将其删除,就好像有人在打字,犯了一个错误,又被删除回到错误的地方,然后一直在那里打字一样。

到目前为止,我所能做的就是把它们写在同一行上:

import sys, time
write = sys.stdout.write

for c in text:  
    write(c)
    time.sleep(.5)

Tags: textinimport程序fortime地方错误
3条回答
write('\b')  # <-- backup 1-character

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

print(text, end="\r")

只是为了说明@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

相关问题 更多 >