萬盛學電腦網

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

Python ljust() 方法詳解:字串靠左填充對齊

方法簽名

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

行為定義

回傳長度至少為 width 的新字串,原字串靠左,右側以 fillchar 填充。若 len(s) >= width,直接回傳原字串副本。

基本範例

>> 'hello'.ljust(10)
'hello     '
>>> 'hello'.ljust(10, '-')
'hello-----'
>>> 'hello'.ljust(3)
'hello'   # 原字串較長,不截斷
>>> ''.ljust(5, '*')
'*****'

實際應用場景

1. 命令列輸出對齊表格

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      

2. 固定寬度日誌格式

輸出:

[14:32:10] INFO     Server started
[14:32:10] DEBUG    Connection established
[14:32:10] ERROR    Timeout

3. 產生固定長度識別碼

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。
  • 對包含寬字元 (中文、Emoji) 的字串,ljust 以碼位數計算寬度,終端機顯示可能對不齊;需搭配 wcwidth 計算顯示寬度後再填充。
  • 原字串不變更,回傳新字串。
copyright © 萬盛學電腦網 all rights reserved