Split long column into several columns and print them side by side

383 Views Asked by At

Using this code:

import string


for i, j in enumerate(string.ascii_uppercase, 1):
    print('{}: {}'.format(i, j))

I get the following output:

1: A
2: B
3: C
4: D
5: E
6: F
7: G
8: H
9: I
10: J
11: K
12: L
13: M
14: N
15: O
...

What I am looking for is this:

0: A              5: F             ....
1: B              6: G
2: C              7: H
3: D              8: I
4: E              9: J
5: F              10: K

Is there a way to split a long column into smaller ones and print them side by side?

(Note: the example above is simply for illustrating the output. The actual contents printed can be very different)

2

There are 2 best solutions below

0
On BEST ANSWER

For Python3 , You can try this function if you need column wise printing -

def listPrinter(lst, cols):
    l = len(lst)
    rs = int(l/cols)
    for i in range(rs):
        for j in range(cols):
            print(lst[i + rs*j] , end='\t')
        print('')

Please note, the argument lst to the above function is the list of what is to be printed.

Then call this function using -

lst = []        
for i, j in enumerate(string.ascii_uppercase, 1):
    lst.append('{}: {}'.format(i, j))

listPrinter(lst,2)

This would output -

1: A    14: N
2: B    15: O
3: C    16: P
4: D    17: Q
5: E    18: R
6: F    19: S
7: G    20: T
8: H    21: U
9: I    22: V
10: J   23: W
11: K   24: X
12: L   25: Y
13: M   26: Z
0
On

Here's an easier way to do it without changing up your script:

import string

for i, j in enumerate(string.ascii_uppercase, 1):
    if(i%2==0):
        print('{}: {}'.format(i, j))
    else:
        print('{}: {}\t'.format(i, j)),