str.ljust(width[, fillchar])、rjust、center 是字串欄位對齊的三大內建方法。支援自訂填充字元,適用於表格輸出、日誌對齊、固定寬度格式產生。
s.ljust(width, fillchar=' ') # 左對齊,右側填充
s.rjust(width, fillchar=' ') # 右對齊,左側填充
s.center(width, fillchar=' ') # 置中,兩側填充 (左側優先少一字元)
# 參數:
# width: 目標總寬度 (含原字串),<= len(s) 時回傳原字串
# fillchar: 單一字元字串,預設空格
s = 'Hello!'
print(s.ljust(10, '+')) # 'Hello!++++'
print(s.rjust(10, '+')) # '++++Hello!'
print(s.center(10, '+')) # '++Hello!++'
# 寬度不足時
print(s.ljust(5)) # 'Hello!' (原樣回傳)
data = [
('產品名稱', '單價', '數量', '小計'),
('蘋果', 30, 5, 150),
('香蕉', 20, 12, 240),
('橘子', 25, 8, 200),
]
# 計算欄寬
col_widths = [max(len(str(row[i])) for row in data) for i in range(4)]
# 格式化列印
for row in data:
line = (
str(row[0]).ljust(col_widths[0]) + ' | ' +
str(row[1]).rjust(col_widths[1]) + ' | ' +
str(row[2]).rjust(col_widths[2]) + ' | ' +
str(row[3]).rjust(col_widths[3])
)
print(line)
# 輸出:
# 產品名稱 | 單價 | 數量 | 小計
# 蘋果 | 30 | 5 | 150
# 香蕉 | 20 | 12 | 240
# 橘子 | 25 | 8 | 200
# 相同效果,語法更統一
'{:<10}'.format('Hello!') # 左對齊
'{:>10}'.format('Hello!') # 右對齊
'{:^10}'.format('Hello!') # 置中
'{:+<10}'.format('Hello!') # 自訂填充字元
'{:0>8}'.format(42) # 數字前導零: '00000042'
| 方法 | format 對應 | f-string 對應 | 適用場景 |
|---|---|---|---|
ljust | {: | f'{s: | 簡單左對齊、舊版本相容 |
rjust | {:>w} | f'{s:>w}' | 數字右對齊、代碼對齊 |
center | {:^w} | f'{s:^w}' | 標題置中、視覺置中 |
zfill | {:0>w} | f'{n:0{w}d}' | 數字前導零 (專用) |
fillchar 必須是長度 1 的字串,否則 TypeErrorljust 計算的是字元數而非顯示寬度,需用 wcwidth 庫或手動調整掌握三大對齊方法與 format/f-string 對應,能快速產出整齊的文字報表與日誌。