Anush Kini
Anush Kini

Reputation: 13

Aligning lines in python

I have written a code to print a snake and ladder grid. I want the numbers to be aligned such that they are in a straight vertical line. My code is:

for i in range(100,0,-1):
    if i%20 == 0:
            for i in range(i,i-10,-1):
                    print(i, end = "    ")
            print()

    elif i%10 == 0:
            for i in range(i-9,i+1):
                    print(i, end = "    ")
            print()

The present output is:

100    99    98    97    96    95    94    93    92    91    
81    82    83    84    85    86    87    88    89    90    
80    79    78    77    76    75    74    73    72    71    
61    62    63    64    65    66    67    68    69    70    
60    59    58    57    56    55    54    53    52    51    
41    42    43    44    45    46    47    48    49    50    
40    39    38    37    36    35    34    33    32    31    
21    22    23    24    25    26    27    28    29    30    
20    19    18    17    16    15    14    13    12    11    
1    2    3    4    5    6    7    8    9    10    

Upvotes: 0

Views: 294

Answers (1)

J-L
J-L

Reputation: 1901

If you're using Python3, try replacing your:

print(i, end = "    ")

lines with:

print(format(i, '6d'), end='')

If you must have the numbers left-justified, try this instead:

print('{:<6d}'.format(i), end='')

These will account for the fact that not every number has the same amount of digits, yet you want every number to take up the same amount of space.

Upvotes: 1

Related Questions