1. ljust、rjust、center
1 In [7]: s = 'abc' 2 3 In [8]: s.ljust(20) 4 Out[8]: 'abc ' 5 6 In [9]: s.ljust(20, '=') 7 Out[9]: 'abc=================' 8 9 In [10]: s.rjust(20, '=') 10 Out[10]: '=================abc' 11 12 In [11]: s.center(20) 13 Out[11]: ' abc '
2.format
In [12]: format(s,'<20') Out[12]: 'abc ' In [13]: format(s,'>20') Out[13]: ' abc' In [14]: format(s,'^20') Out[14]: ' abc '
以字典中最长的key值为基准对齐
d = dict( english=109.0, math=0.05, chinese=100, height=195, weight=80 ) # 获取字典key的最大长度 w = max(map(len, d.keys())) for k in d: print(k.ljust(w), ':', d[k])