str.ljust(width, fillchar=' ') -> str
回傳長度至少為 width 的新字串,原字串靠左,右側以 fillchar 填充。若 len(s) >= width,直接回傳原字串副本。
>> 'hello'.ljust(10)
'hello '
>>> 'hello'.ljust(10, '-')
'hello-----'
>>> 'hello'.ljust(3)
'hello' # 原字串較長,不截斷
>>> ''.ljust(5, '*')
'*****'
data = [
('Name', 'Age', 'City'),
('Alice', 30, 'Taipei'),
('Bob', 25, 'New York'),
('Charlie', 35, 'London'),
]
col_widths = [10, 5, 12]
header = ''.join(h.ljust(w) for h, w in zip(data[0], col_widths))
print(header)
print('-' * sum(col_widths))
for row in data[1:]:
line = ''.join(str(v).ljust(w) for v, w in zip(row, col_widths))
print(line)
輸出:
Name Age City ---------------------------- Alice 30 Taipei Bob 25 New York Charlie 35 London
輸出:
[14:32:10] INFO Server started [14:32:10] DEBUG Connection established [14:32:10] ERROR Timeout
def make_id(prefix, num, total_len=12):
return (prefix + str(num)).ljust(total_len, '0')
print(make_id('ORD', 42)) # 'ORD420000000'
print(make_id('INV', 12345)) # 'INV12345000'
rjust()、center()| 方法 | 對齊 | 範例 |
|---|---|---|
ljust(10, '-') | 靠左 | 'hi------' |
rjust(10, '-') | 靠右 | '------hi' |
center(10, '-') | 置中 | '----hi----' |
format / f-string 替代方案>> f'{"hello":<10}' # 靠左
'hello '
>>> f'{"hello":->10}' # 靠左,自訂填充字
'hello-----'
>>> f'{"hello":>10}' # 靠右
' hello'
>>> f'{"hello":^10}' # 置中
' hello '
格式化字串語法更強大 (支援數字格式化、正負號、千分位等),現代程式碼建議優先使用 f-string。
fillchar 必須是長度為 1 的字串,否則拋出 TypeError。ljust 以碼位數計算寬度,終端機顯示可能對不齊;需搭配 wcwidth 計算顯示寬度後再填充。