eager coder eager coder - 5 months ago 28
Python Question

traverse and printing strings in python column wise

Is there a way to print a string in Python, to get a character column - wise?

Maybe like [ [ o n ] , [ * o ] ] as below
input is given in array or list as series of words in matrix form

on
*o
the output should come like below in column wise


  1. o

  2. no


Answer Source

You could do it like this:

from itertools import zip_longest

strings = ['First,', 'long second,', 'and third!']

lines = zip_longest(*strings, fillvalue=' ')
for line in lines:
    print(''.join(line))

Fla
ion
rnd
sg 
t t
,sh
 ei
 cr
 od
 n!
 d 
 , 

zip_longest lets you iterate on each string, adding spaces as fillvalue to the shortest ones.

list(lines) will be `[('F', 'l', 'a'), ('i', 'o', 'n'), ...]

We can then print each line by joining the letters in each tuple.

You can add spaces between the columns:

for line in lines:
    print('  '.join(line))

F  l  a
i  o  n
r  n  d
s  g   
t     t
,  s  h
   e  i
   c  r
   o  d
   n  !
   d   
   ,   

If you don't want to print *, just replace them with spaces:

from itertools import zip_longest
strings = ['ant', '*oi', '**p']
lines = zip_longest(*strings, fillvalue=' ')


for line in lines:
    print(''.join(line).replace('*',' '))
# a    
# n o  
# t i p