tryingtobeastoic
tryingtobeastoic

Reputation: 195

How to iterate through string elements in a list side-by-side?

I have a list:

cl = ["Food", "Clothing", "Automation"]

I want to print each character in each string of this list side-by-side:

 F  C  A  
 o  l  u  
 o  o  t  
 d  t  o  
    h     
    i     
    n     
    g

I have managed to do this so far:

cl = ["Food", "Clothing", "Automation"]

for i in cl:
    for j in i:
        print(j)

Output:

F
o
o
d
C
l
o
t
h
i
n
g
A
u
t
o
m
a
t
i
o
n

How can I achieve my desired outcome?

Upvotes: 0

Views: 50

Answers (1)

Djaouad
Djaouad

Reputation: 22776

You can use itertools.zip_longest:

from itertools import zip_longest

cl = ['Food', 'Clothing', 'Automation']

for letters in zip_longest(*cl, fillvalue = ' '):
  print(*letters, sep = '  ')

Output:

F  C  A
o  l  u
o  o  t
d  t  o
   h  m
   i  a
   n  t
   g  i
      o
      n

Upvotes: 4

Related Questions