3

I have the below

foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
while True:
    print choice(foo)

The output is:

a
c
a
e
...

I want the terminal output to overwrite the old output on the same line

thanks

  • 1
    Instead of writing backspace characters, I would recommend usind the curses module. – rlms Dec 10 '13 at 21:20

2 Answers2

2

you can remove the old output by

import sys
sys.stdout.write( '\b' ) # removes the last outputed character

and you possibly need to use flush after each print

sys.stdout.flush()

something like this:

from __future__ import print_function
import time

for j in range( 10 ):
   print( j, end='' )
   sys.stdout.flush()
   time.sleep( 2 )
   sys.stdout.write( '\b' )
behzad.nouri
  • 74,723
  • 18
  • 126
  • 124
2

You have two things to override: one, python will automatically add a newline when you print. Override that by adding a comma at the end, like @SteveP says (or said at least :-)).

Next, you need to explicitly add a carriage return control character to the front of your string so that the terminal output will overwrite your previous output, as opposed to appending it to the end.

foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
while True:
    print '\r' + choice(foo),

(might want a time.sleep in there so you can actually see what's happening)

roippi
  • 25,533
  • 4
  • 48
  • 73