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}\t{1:^10}\t{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}\t{1:{3}^10}\t{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))) 

 

 

 

 

 

用0填充:Python zfill()方法

描述

Python zfill() 方法返回指定長度的字符串,原字符串右對齊,前面填充0。

語法

zfill()方法語法:

str.zfill(width)

參數

  • width -- 指定字符串的長度。原字符串右對齊,前面填充0。

返回值

返回指定長度的字符串。

實例

以下實例展示了 zfill()函數的使用方法:

#!/usr/bin/python

str = "this is string example....wow!!!";

print str.zfill(40);
print str.zfill(50);

 

以上實例輸出結果如下:

00000000this is string example....wow!!!
000000000000000000this is string example....wow!!!

 

 

如果不想用0填充:

使用

Str.rjust() 右對齊

或者

Str.ljust() 左對齊

或者

Str.center() 居中的方法有序列的輸出。

>>> dic = {
    "name": "botoo",
    "url": "http://www.123.com",
    "page": "88",
    "isNonProfit": "true",
    "address": "china",
    }
>>> 
>>> d = max(map(len, dic.keys()))  #獲取key的最大值
>>> 
>>> for k in dic:
    print(k.ljust(d),":",dic[k])

    
name        : botoo
url         : http://www.123.com
page        : 88
isNonProfit : true
address     : china
>>> for k in dic:
    print(k.rjust(d),":",dic[k])

    
       name : botoo
        url : http://www.123.com
       page : 88
isNonProfit : true
    address : china
>>> for k in dic:
    print(k.center(d),":",dic[k])

    
    name    : botoo
    url     : http://www.123.com
    page    : 88
isNonProfit : true
  address   : china
>>>

 

 

>>> s = "adc"
>>> s.ljust(20,"+")
'adc+++++++++++++++++'
>>> s.rjust(20)
'                 adc'
>>> s.center(20,"+")
'++++++++adc+++++++++'
>>>

 

"+"可以換成自己想填充的字符。

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM