helix helix - 6 months ago 17
Python Question

python - printing items inline in IPython

I need to print everything inline dynamically in a for loop in an IPython notebook. I am using python 2.7. I used the code:

for i in xrange(10):
print "." ,
#some computation and no print statement


and even used:

for i in xrange(10):
print "\b."
#some computation and no print statement


but both of the above solutions doesn't seem to work in IPython notebooks.

what I need is:
..........
and what the above snippets are printing is:

.
.
.
.
.
.
.
.
.
.


Any and every help is appreciated.

Answer

This will work on both Python 2 and Python 3:

from __future__ import print_function

for i in range(10):
    print('.', end='')

You can also pass flush=True keyword argument to force it to flush the buffer instantly.

You can also overwrite a previous line using '\r', her's a simple example:

import time

for i in range(10):
    time.sleep(0.2)
    print('\r{} / 10'.format(i + 1, 10), end='')