7

How can I edit a string that I just printed? For example, for a countdown counter (First prints 30, then changes it to 29 and so on)

Thanks.

Alex
  • 107
  • 1
  • 4
  • 1
    This is just a variant on the [spinning cursor problem](http://stackoverflow.com/questions/4995733/how-to-create-a-spinning-command-line-cursor-using-python). – ire_and_curses Mar 30 '11 at 20:52

5 Answers5

7

Print a carriage return \r and it will take the cursor back to the beginning on the line. Ensure you don't print a newline \n at the end, because you can't backtrack lines. This means you have have to do something like:

import time
import sys
sys.stdout.write('29 seconds remaining')
time.sleep(1)
sys.stdout.write('\r28 seconds remaining')

(As opposed to using print, which does add a newline to the end of what it writes to stdout.)

bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
1

If you're targeting Unix/Linux then "curses" makes writing console programs really easy. It handles color, cursor positioning etc. Check out the python wrapper: http://docs.python.org/library/curses.html

das_weezul
  • 6,082
  • 2
  • 28
  • 33
0

If you're on a xterm-like output device, the way you do this is by OVERWRITING the output. You have to ensure that when you write the number you end with a carriage-return (without a newline), which moves the cursor back to the start of the line without advancing to the next line. The next output you write will replace the current displayed number.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
0

You can not change what you printed. What's printed is printed. But, like bradley.ayers said you can return to the beginning of the line and print something new over the old value.

Iulius Curt
  • 4,984
  • 4
  • 31
  • 55
0

You can use the readline module, which can also provide customized completion and command history.

Joschua
  • 5,816
  • 5
  • 33
  • 44