簡體   English   中英

刪除 Python 打印行中的字符

[英]Delete Characters in Python Printed Line

我正在編寫一個程序,我希望光標在同一行上打印字母,但隨后也將它們刪除,就好像有人在打字,犯了一個錯誤,刪除回錯誤,然后繼續從那里打字。

到目前為止,我所擁有的只是將它們寫在同一行上的能力:

import sys, time
write = sys.stdout.write

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

只是為了說明@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] Sven Marnachin 在 Python Remove and Replace Printed Items 中的這個答案
[2] 關於構建進度條的博客文章

當您使用print() ,您可以將 end 設置為\\r ,它將用新文本替換該行中的文本。

print(text, end="\r")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM