16
votes

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)
3
You might want to look at the curses package for unix, or an alternative for windows. The one I've used is msvcrt. If you're just trying to fake out the user in a console then the '\b' character will work. - jgritty
You can format code nicely by just indenting it by four spaces (or alternatively, by pasting and selecting it and then clicking the code button). - Niklas B.

3 Answers

27
votes
write('\b')  # <-- backup 1-character
9
votes

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

4
votes

When you are using print(), you can set end as \r, which will replace the text in the line with the new text.

print(text, end="\r")