I have a Python program I am writing and I want it to be able to change text after it is printed. For example, let's say I want to print "hello" and erase one letter every second. How would I go about doing that?
Also, I heard about curses but I can't get that to work, and I do not want to simply create new lines until the old text is off the screen.
Here's one way to do it.
print 'hello',
sys.stdout.flush()
...
print '\rhell ',
sys.stdout.flush()
...
print '\rhel ',
sys.stdout.flush()
You can probably also get clever with ANSI escapes. Something like
sys.stdout.write('hello')
sys.stdout.flush()
for _ in range(5):
time.sleep(1)
sys.stdout.write('\033[D \033[D')
sys.stdout.flush()
For multi-line output, you can also clear the screen each time and reprint the entire thing:
from time import sleep
import os
def cls():
os.system('cls' if os.name=='nt' else 'clear')
message = 'hello'
for i in range(len(message), 0, -1):
cls()
print message[:i]
sleep(1)
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