How to center align columns of different lengths using numpy.savetxt in Python?
Question: I have several lists that contain both strings and floats as their elements.

    
    
    import numpy as num
    
    COLUMN_1 = ['KIC 7742534', 'Variable Star of RR Lyr type' , 'V* V368 Lyr',
            'KIC 7742534', '4.0', '0.4564816']
    
    COLUMN_2 = ['KIC 76', 'Variable Star' , 'V* V33 Lyr',
            'KIC 76', '5.0', '0.45']
    
    DAT = num.column_stack((COLUMN_1, COLUMN_2))
    num.savetxt('SAVETXT.txt', DAT, delimiter=' ', fmt='{:^10}'.format('%s'))
    

The output I get when running this file is the following:

    
    
    KIC 7742534    ,    KIC 76    
    Variable Star of RR Lyr type    ,    Variable Star    
    V* V368 Lyr    ,    V* V33 Lyr    
    KIC 7742534    ,    KIC 76    
    4.0    ,    5.0    
    0.4564816    ,    0.45     
    

The ideal output would look like this (including an aligned header)

    
    
    #ELEMENT1                            ELEMENT2
    KIC 7742534                     ,    KIC 76    
    Variable Star of RR Lyr type    ,    Variable Star    
    V* V368 Lyr                     ,    V* V33 Lyr    
    KIC 7742534                     ,    KIC 76    
    4.0                             ,    5.0    
    0.4564816                       ,    0.45   
    

How could I get an output like this (with aligned header), if the strings
don't have a max width defined. I have tried modifying the format of the
strings (fmt), but no luck so far.

-Thanks!


Answer: You will need to calculate the maximum string length of of the longest row of
your output (or input depending on how you look at it), which a method similar
to

    
    
    max_len = max(max(map(len,l)) for l in zip(COLUMN_1,COLUMN_2))
    

Will achieve. After that you need to change the `fmt` parameters dynamically
based on the value of max_len which you can do like so:

`fmt=('{:^%d}' % max_len).format('%s')`

The following non-numpy example shows the expected output:

    
    
    with open('ofile.txt','w+') as f:
        max_len = max(max(map(len,l)) for l in zip(COLUMN_1,COLUMN_2))
        for line in zip(COLUMN_1,COLUMN_2):
            f.write(','.join(('{:<%s}' % (max_len)).format(e) for e in line)+'\n')
    

Produces a text file `ofile.txt` containing:

    
    
    KIC 7742534                 ,KIC 76                      
    Variable Star of RR Lyr type,Variable Star               
    V* V368 Lyr                 ,V* V33 Lyr                  
    KIC 7742534                 ,KIC 76                      
    4.0                         ,5.0                         
    0.4564816                   ,0.45          
    

