20

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)
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
JShoe
  • 3,186
  • 9
  • 38
  • 61
  • 2
    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. Mar 30 '12 at 20:21
  • 2
    You might want to look at the [curses](http://docs.python.org/library/curses.html) package for unix, or an alternative for windows. The one I've used is [msvcrt](http://docs.python.org/library/msvcrt.html). If you're just trying to fake out the user in a console then the '\b' character will work. – jgritty Mar 30 '12 at 20:20
  • Does this answer your question? [Remove and Replace Printed items](https://stackoverflow.com/questions/5290994/remove-and-replace-printed-items) – Tomato Master Feb 16 '22 at 08:13

3 Answers3

28
write('\b')  # <-- backup 1-character
user590028
  • 11,364
  • 3
  • 40
  • 57
14

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

Tai
  • 7,684
  • 3
  • 29
  • 49
6

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

print(text, end="\r")
RCRalph
  • 355
  • 6
  • 17