format - How to center align columns of different lengths using numpy.savetxt in Python? -


i have several lists contain both strings , floats elements.

import numpy 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 when running file 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 (including 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 output (with aligned header), if strings don't have max width defined. have tried modifying format of strings (fmt), no luck far.

-thanks!

you need calculate maximum string length of of longest row of output (or input depending on how @ it), method similar

max_len = max(max(map(len,l)) l in zip(column_1,column_2)) 

will achieve. after need change fmt parameters dynamically based on value of max_len can so:

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

the following non-numpy example shows expected output:

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

produces 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           

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -