SB2000
SB2000

Reputation: 31

How to make my code formatted properly in columns

I want my code to come out looking like the image below. My code is below that

nums = list(range(1,101))

chunks = []

for i in range(1, len(nums)+1):
    if i % 10 == 0:
        print(i, end = " ")
        print()
    else:
        print(i, end = " ")

Upvotes: 2

Views: 192

Answers (2)

Rick
Rick

Reputation: 45311

Use the two-argument version of iter and itertools.islice to get your rows. Use f-strings to format your integer strings. Use join to put together the columns and rows.

import itertools

nums = list(range(1,101))
iter_nums = iter(nums)

columns = 10
rows = list(iter(lambda: list(itertools.islice(iter_nums, columns)), []))
print("\n".join("".join(f"{x:>5d}" for x in row) for row in rows))

Upvotes: 0

AKX
AKX

Reputation: 169378

Turn the numbers into strings with str(), then use rjust to pad the string to 5 characters.

You can also use some cleverness with end= to simplify the if: else: things into just one print.

for i in range(1, 101):
    end = ("\n" if (i - 1) % 10 == 9 else "")
    print(str(i).rjust(5), end=end)
$ python so69197817.py
    1    2    3    4    5    6    7    8    9   10
   11   12   13   14   15   16   17   18   19   20
   21   22   23   24   25   26   27   28   29   30
   31   32   33   34   35   36   37   38   39   40
   41   42   43   44   45   46   47   48   49   50
   51   52   53   54   55   56   57   58   59   60
   61   62   63   64   65   66   67   68   69   70
   71   72   73   74   75   76   77   78   79   80
   81   82   83   84   85   86   87   88   89   90
   91   92   93   94   95   96   97   98   99  100

Upvotes: 4

Related Questions