Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing multiple strings vertically

I have a list of string that I would like to print vertically side by side.

from itertools import zip_longest

x = ["Please","help","out"]
string = ''

for word in list_of_words:
    string  += word + " "
for x in zip_longest(*string.split(), fillvalue=' '):
    print (' '.join(x))

this works but I would like to do this without importing anything.

Input: x = ["Please","help","out"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output:

    P h o
    l e u 
    e l t
    a p  
    s  
    e

>Solution :

Here’s a simple option:

words = ["Please", "help", "out"]
maxlen = max(len(w) for w in words)

for i in range(maxlen):
    row = []
    for w in words:
        try:
            row.append(w[i])
        except IndexError:
            row.append(' ')
    print(' '.join(row))

Basically, compute the max length of all words. Iterate from 0 to maxlen and try to pick the i-th character from each word. If this fails, use a space instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading