futurevilla216 futurevilla216 - 12 days ago 6
Python Question

In Python, how to change text after it's printed?

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.

Answer

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()