简体   繁体   中英

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

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
[2] Blog post about building progress bars

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

print(text, end="\r")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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