python 輸出對齊

幾種不一樣類型的輸出對齊總結:python

 

先看效果:c++

 

 

 

 

 

 採用.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

可是在打印多組中文的時候,不是每組中文的字符串寬度都同樣,當中文字符寬度不夠的時候,程序採用西文空格填充,中西文空格寬度不同,就會致使輸出文本不整齊this

以下,打印中國高校排名。編碼

 

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因此會填充西文空格,就會致使字符的實際寬度長短不一。url

 

 

 


解決方法:寬度不夠時採用中文空格填充spa

中文空格的編碼爲chr(12288)3d

 

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()方法

描述code

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

語法

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+++++++++'
>>>

 

"+"能夠換成本身想填充的字符。

相關文章
相關標籤/搜索