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.
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
.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With