python输出格式对齐问题

采用.format打印输出时,可以定义输出字符串的输出宽度,在 ':' 后传入一个整数, 可以保证该域至少有这么多的宽度。 用于美化表格时很有用。

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> for name, number in table.items():
...     print('{0:10} ==> {1:10d}'.format(name, number))
...
Runoob     ==>          2
Taobao     ==>          3
Google     ==>          1

但是在打印多组中文的时候,不是每组中文的字符串宽度都一样,当中文字符宽度不够的时候,程序采用西文空格填充,中西文空格宽度不一样,就会导致输出文本不整齐

如下,打印中国高校排名

tplt = "{0:^10}	{1:^10}	{2:^10}"
    print(tplt.format("学校名称", "位置", "分数"))
    for i in range(num):
        u = ulist[i]
        print(tplt.format(u[0], u[1], u[2]))

把字符串宽度都定义为10,但是中文本身的宽度都不到10所以会填充西文空格,就会导致字符的实际宽度长短不一

解决方法:宽度不够时采用中文空格填充

中文空格的编码为chr(12288)

tplt = "{0:{3}^10}	{1:{3}^10}	{2:^10}"
    print(tplt.format("学校名称", "位置", "分数", chr(12288)))
    for i in range(num):
        u = ulist[i]
        print(tplt.format(u[0], u[1], u[2], chr(12288)))

原文地址:https://www.cnblogs.com/zhz-8919/p/9767357.html