Reputation: 107
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.
Upvotes: 7
Views: 4400
Reputation: 6034
You can use the readline module, which can also provide customized completion and command history.
Upvotes: 0
Reputation: 6142
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
Upvotes: 1
Reputation: 5114
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.
Upvotes: 0
Reputation: 86774
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.
Upvotes: 0
Reputation: 38382
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
.)
Upvotes: 7