-1

Is there a way to do printf formatting to strings in Python? Something like this where the count x is rewritten every time instead of echoing to a new line.

x=0
while [[ $x -lt 10 ]]; do
    x=$((x+1))
    printf '%s\r'"Processing page ${x}"
    sleep 1
done
I0_ol
  • 1,054
  • 1
  • 14
  • 28

2 Answers2

1

In Python 3 (Daiwei Chen's answer covers Python 2.6+ also):

import time
x = 0
while x < 10:
    x += 1
    print('\rProcessing Page {0}'.format(x), end='')
    time.sleep(1)

Adding a carriage return to the beginning and removing the new line from the end with end='' will overwrite the current line.

ZuluDeltaNiner
  • 725
  • 2
  • 11
  • 27
1

In Python 3.x, the print function takes in an additional argument for the end parameter.

>>> print('foo', end='')
foo

>>> for i in range(10):
print('foo', end='')
foofoofoofoofoofoofoofoofoofoo

Of course, if you're using Python >= 2.6, you'll need to import print_function from __future__.

>>> from __future__ import print_function