0

I want to print a constant message in the form of:

Time remaining: X Seconds

Where X will be a count-down number. But I don't want to have an output like:

Time remaining: 5 Seconds
Time remaining: 4 Seconds
Time remaining: 3 Seconds
Time remaining: 2 Seconds ...

I want only the number to change in the same text line. Is it possible using escape sequences or other way?

Demis
  • 197
  • 9

4 Answers4

1

Yes you can!

Please refer to the answer found here

The code has been modified a little to look more like you want, and to use the more recent string formatting.

from time import sleep
import sys

for i in range(10):
    sys.stdout.write("\rTime remaining: {} Seconds".format(i))
    sys.stdout.flush()
    sleep(1)
print '\n'
Kevin Glasson
  • 401
  • 2
  • 11
  • No, this is not what i'm asking ... I want the same first line to mutate only at the position of the number. That's why I refered to it as "dynamic". – Demis Mar 20 '18 at 01:20
1

Add argument end='\r' in your print function.

import time

x = 10
width = str(len(str(x)))
while x > 0:
    print('Time remaining: {{:{:}}} seconds'.format(width).format(x), end='\r')
    x -= 1
    time.sleep(1)

You may also refer to this post.

pe-perry
  • 2,403
  • 2
  • 16
  • 27
1

I found this link

And got it to work. The "stuff" is there to show that texted displayed before the count down is not getting 'clear'ed

import time
import sys

num = 5
print('stuff')

while(num >= 0):
    sys.stdout.write("\rTime remaining: {} Seconds".format(num))
    sys.stdout.flush()
    time.sleep(1)
    num -= 1
dkh
  • 23
  • 5
1

You can set end= " " to remove newlines and add a carriage return '\r'

So the correct program which should work for you is:

n = 100
while n > 0:
    print('\rTime remaining: {} Seconds'.format(n), end=' ')
    n -= 1
    time.sleep(1)
print(' ')