void.pointer
void.pointer

Reputation: 26365

How to pad string based on digits in a number?

Suppose I have an arbitrary number:

my_number = 898

I want to create a loop that counts up to that number, using a padding for the current count equal to the digits of that maximum number. In other words, if my_number is 5 digits long, then when the count is at 1 it should read ----1, where each - is one space in the padding. Likewise, if we're at number 500 then it should be padded like so: --500. Example loop:

for i in range(my_number):
    print( '{}: Current Number'.format(i) )

I hope I'm clear. I just don't know what the 'pythonic' way of doing this would be. I imagine there is some clean way of doing this in python but I can't help but think of a cumbersome solution that would require several lines of code.

Upvotes: 1

Views: 226

Answers (2)

TerryA
TerryA

Reputation: 59984

Something like this?

>>> my_number = 15
>>> for i in range(my_number):
...     strung = str(i)
...     print('-'*(len(str(my_number))-len(strung))+strung) # If you want spaces instead of dashes, do print(' '*(len(.......
... 
-0
-1
-2
-3
-4
-5
-6
-7
-8
-9
10
11
12
13
14

Upvotes: 4

awesoon
awesoon

Reputation: 33671

You could use right-aligned format specifier for it:

In [23]: num = 15

In [24]: for x in range(num):
    print("{0:>{1}}".format(x, len(str(num))))
   ....:     
 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

Upvotes: 5

Related Questions