1

I have a loop:

for i in range(10):
    print i

and it print :

1
2
...
8
9

OK

but I'm searching to make a unique line which actualize for each iteration like this :

for i in range(10):
    magic_print "this is the iteration " + i + " /10"

with a result like:

"this is the iteration <i> /10"

<i> changing dynamically

Thanks !

Covich
  • 2,544
  • 4
  • 26
  • 37

2 Answers2

2

As I understand your question, you would like to overwrite previous prints and count up. See this answer: https://stackoverflow.com/a/5419488/4362607

I edited the answer according to PM 2Ring's suggestions. Thanks!

import sys
import time

def counter():
    for x in range(10):
        print '{0}\r'.format(x),
        sys.stdout.flush()
        time.sleep(1)
    print

counter()
Community
  • 1
  • 1
Godrebh
  • 354
  • 2
  • 13
  • 1
    Almost. You probably need `sys.stdout.flush()` after the `print` statement. And you could put a `time.sleep(1)` into the loop so we can see what's happening. – PM 2Ring Dec 18 '14 at 09:08
0

the solution is the format function from the str object

for i in range(10):
    print "this is the iteration {} /10".format(i)
markcial
  • 9,041
  • 4
  • 31
  • 41