1

I am aware that this has been posted many times, but I can't find a working solution for my problem. Here is my script:

from time import sleep
x = 100
for i in range(0, 100):
    print(x, end="\r")
    x -=1
    sleep(1)

When I run this it prints:

100
990
980
970

except on one line and the text gets replaced and it continues. I want it to do this:

100
99
98
97

on one line and it goes all the way to zero and the text gets replaced. How can I do this?

TheRealTengri
  • 1,201
  • 1
  • 7
  • 17
  • See this: https://stackoverflow.com/questions/6169217/replace-console-output-in-python – Jon Feb 14 '20 at 17:58
  • `\r` doesn't clear the current line; it only moves the cursor to the beginning of the current line. Subsequent writes only overwrite whatever is necessary to write that line, with no knowledge of what had been written previously. – chepner Feb 14 '20 at 18:03

2 Answers2

2

Formatting your string works:

import time

for x in range(100, 0, -1):
    time.sleep(1)
    print(f'{x:3d}', end='\r')

This formats you integers right adjusted with a width of three digits and you can see the "shorter" numbers. Or, use f'{x: <3d}' to have the numbers line up at the left (as @Olvin Roght suggested). The f in front makes it it a format string. The content inside the {} will be replaced, in this case with the value of x. The part after the : is the formatting. Here: a decimal integer with three digits.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
0

You can use str.ljust():

print(str(x).ljust(3), end="\r")
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35