string.format,不同的长度中断表

时间:2013-06-14 15:37:58

标签: python list formatting

我正在尝试将列表列表格式化为表格。它主要起作用,但如果一个元素太长,它似乎打破了桌子。知道为什么会发生这种情况或者如何使用这种方法确保格式良好的表吗?

 table_data = [['vlan1', '0013.F200.0058', '192.168.2.2'], 
                 ['vlan20', '0013.F200.0058', '192.168.30.2'],
                 ['vlan20', '0010.600a.7026', '192.168.30.4'],
                 ['vlan20', '70ca.9b99.6a82', '192.168.30.1'],
                 ['vlan21', '0013.F200.0058', '192.168.222.222'], 
                 ['vlan100', '0013.F200.0058', '192.168.110.2'],
                 ['vlan2100', '0013.F200.0058', '192.168.222.223']]



for i in table_data:
        interface,mac,ip = i
        print "Internet  {}\t {:>18s}\t{:>7s}\t  {:<8s}".format(ip, mac,'ARPA' ,interface)


Protocol  Address            Hardware Addr         Type   Interface                     
--------  -------            -------------         ----   ---------                     
Internet  192.168.2.2        0013.F200.0058        ARPA   vlan1                 
Internet  192.168.30.2       0013.F200.0058        ARPA   vlan20                
Internet  192.168.30.4       0010.600a.7026        ARPA   vlan20                
Internet  192.168.30.1       70ca.9b99.6a82        ARPA   vlan20                
Internet  192.168.222.222            0013.F200.0058        ARPA   vlan21        
Internet  192.168.110.2      0013.F200.0058        ARPA   vlan100               
Internet  192.168.222.223            0013.F200.0058        ARPA   vlan2100  

1 个答案:

答案 0 :(得分:2)

你可以使用左对齐格式不是吗? 请查看此文档Format Specification Mini-Language

for i in table_data:
     interface,mac,ip = i
     print '{:<20s}{:<20s}{:<20s}{s}'.format(ip, mac,'ARPA' ,interface)