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

How to align strings in columns?

I am trying to print out a custom format but am facing an issue.

header = ['string', 'longer string', 'str']
header1, header2, header3 = header
data = ['string', 'str', 'longest string']
data1, data2, data3 = data
len1 = len(header1)
len2 = len(header2)
len3 = len(header3)
len_1 = len(data1)
len_2 = len(data2)
len_3 = len(data3)
un = len1 + len2 + len3 + len_1 + len_2 + len_3
un_c = '_' * un
print(f"{un_c}\n|{header1} |{header2} |{header3}| \n |{data1} |{data2} |{data3}|")

Output:

_____________________________________________
|string |longer string |str|
 |string |str |longest string|

The output I want is this:

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

_______________________________________
|string |longer string |str           |
|string |str           |longest string|

I want it to work for all lengths of strings using the len function, but I can’t figure it out at all.

>Solution :

Do it in two parts. First, figure out the size of each column. Then, do the printing based on those sizes.

header = ['string','longer string','str']
data = ['string','str','longest string']
lines = [header] * 3 + [data] * 3

def getsizes(lines):
    maxn = [0] * len(lines[0])
    for row in lines:
        for i,col in enumerate(row):
            maxn[i] = max(maxn[i], len(col)+1)
    return maxn

def maketable(lines):
    sizes = getsizes(lines)
    all = sum(sizes)
    print('_'*(all+len(sizes)) )
    for row in lines:
        print('|',end='')
        for width, col in zip( sizes, row ):
            print( col.ljust(width), end='|' )
        print()

maketable(lines)

Output:

_______________________________________
|string |longer string |str            |
|string |longer string |str            |
|string |longer string |str            |
|string |str           |longest string |
|string |str           |longest string |
|string |str           |longest string |

You could change it to build up a single string, if you need that.

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