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'{"hello":^10}'
' hello '
>>> f'{"hello":-^10}'
'--hello---'
>>> f'{"title":=^30}'
'============title==============='
fillchar 必須長度 1。wcwidth 計算後手動填充。