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?

5 Answers 5

3

You also have the flush parameter in the print method (I just discovered it as well):

from time import sleep

for i in range(10):
    print(f"\rTime remaining: {i} Seconds", end='', flush=True)
    sleep(1)
Sign up to request clarification or add additional context in comments.

Comments

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'

1 Comment

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".
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.

1 Comment

I copied your code but it printed as usual. The post was useful though.
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

Comments

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(' ')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.