1

For example, if I had a range of 10, it would print:

9
8
7

and so on. Then when I have double digits, so with a range of 11, it prints out:

10
9
8

But, I want it to print out with the 9 under the 0 instead. Any way to do this?

3 Answers3

3

You could use str.rjust:

for i in reversed(range(1, 11)):
    print(str(i).rjust(2))

Output:

10
 9
 8
 7
 6
 5
 4
 3
 2
 1
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
0

In Python 3:

for i in range(11)[::-1]:
    print(f"{i:>2}")

If you want three-digit numbers, change the 2 to a 3.

Seth
  • 2,214
  • 1
  • 7
  • 21
0

You can just add a space at the beginning of the number. I just calculate the amount of digits and pad the lower number with spaces

max = 1337
max_len = len(str(max))
for i in reversed(range(max)):
    str_len = len(str(i))
    if max_len > str_len:
        difference = max_len - str_len #calculate amount of needed spaces
        print(" " * difference + str(i)) #pad string with spaces
    else:
        print(i)
statist32
  • 56
  • 3