萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python center() 方法詳解:字串置中填充

方法簽名

str.center(width, fillchar=' ') -> str

行為定義

回傳長度至少為 width 的新字串,原字串置中,兩側以 fillchar 填充。若無法平均分配,右側多一個。若 len(s) >= width,回傳原字串副本。

基本範例

>> 'hello'.center(10)
'  hello   '
>>> 'hello'.center(11)
'  hello    '  # 右側多一個
>>> 'hello'.center(10, '-')
'--hello---'
>>> 'hello'.center(3)
'hello'

實際應用:終端機標題、表格標題列

def print_header(title, width=60, fill='='):
    print(title.center(width, fill))

print_header('系統啟動日誌')
print_header('資料庫連線狀態', fill='-')

輸出:

===============系統啟動日誌================
----------資料庫連線狀態----------

對齊方法家族對照

方法對齊fillchar 位置
ljust(w, c)靠左右側
rjust(w, c)靠右左側
center(w, c)置中兩側 (右側優先)

f-string 替代 (推薦)

>> f'{"hello":^10}'
'  hello   '
>>> f'{"hello":-^10}'
'--hello---'
>>> f'{"title":=^30}'
'============title==============='

注意事項

  • fillchar 必須長度 1。
  • 寬字元 (中文、Emoji) 視覺寬度 ≠ 字元數,終端機對齊會錯位;需用 wcwidth 計算後手動填充。
  • 原字串不變更。
copyright © 萬盛學電腦網 all rights reserved