字串左對齊並填充至指定寬度是報表輸出、日誌格式化、CLI 介面對齊的常見需求。Python ljust() 方法提供簡潔解法:回傳原字串靠左、右側以指定字元填充至目標寬度的新字串。本文詳細說明語法、參數、行為細節與實戰應用。
str.ljust(width[, fillchar])
' '。必須為單一字元。width <= len(str),直接回傳原字串(不截斷)。#!/usr/bin/python3
# 範例 1:基本左對齊(空格填充)
s = "hello"
print(repr(s.ljust(10))) # 'hello '
print(f"|{s.ljust(10)}|") # |hello |
# 範例 2:自訂填充字元
print(repr(s.ljust(10, '0'))) # 'hello00000'
print(repr(s.ljust(10, '-'))) # 'hello-----'
print(repr(s.ljust(10, '*'))) # 'hello*****'
# 範例 3:寬度小於等於字串長度(不截斷)
print(repr(s.ljust(3))) # 'hello'
print(repr(s.ljust(5))) # 'hello'
# 範例 4:中文字串(每字算 1 寬度)
c = "你好"
print(repr(c.ljust(6))) # '你好 '
print(repr(c.ljust(6, '·'))) # '你好····'
# 範例 5:Emoji
e = "😀"
print(repr(e.ljust(4))) # '😀 '
# 範例 6:空字串
print(repr("".ljust(5, 'x'))) # 'xxxxx'
# 錯誤:填充字元長度不為 1
try:
"a".ljust(5, "ab")
except TypeError as e:
print(e) # The fill character must be exactly one character long
# 正確:單一字元
"a".ljust(5, "あ") # 'あああああ'(全形字也可)
"a".ljust(5, " ") # 'a '
data = [
("商品名稱", "價格", "庫存"),
("蘋果", "30", "100"),
("香蕉", "20", "200"),
("超長商品名稱測試", "999", "5")
]
col_widths = [20, 8, 6]
header = "".join(f"{col.ljust(w)}" for col, w in zip(data[0], col_widths))
print(header)
for row in data[1:]:
line = "".join(f"{col.ljust(w)}" for col, w in zip(row, col_widths))
print(line)
def log_entry(level, module, message):
timestamp = "2024-01-15 10:30:45"
return f"{timestamp} {level.ljust(7)} {module.ljust(15)} {message}"
print(log_entry("INFO", "Auth", "User login successful"))
print(log_entry("ERROR", "Database", "Connection timeout"))
# 2024-01-15 10:30:45 INFO Auth User login successful
# 2024-01-15 10:30:45 ERROR Database Connection timeout
menu = [
("1", "新增資料"),
("2", "查詢資料"),
("3", "修改資料"),
("4", "刪除資料"),
("q", "離開系統")
]
for key, desc in menu:
print(f" {key.ljust(3)} {desc}")
# 1 新增資料
# 2 查詢資料
# ...
# q 離開系統
| 方法 | 對齊方向 | 填充位置 | 範例 (width=10, fill='-') |
|---|---|---|---|
| ljust() | 左對齊 | 右側 | "hello-----" |
| rjust() | 右對齊 | 左側 | "-----hello" |
| center() | 置中 | 兩側 | "--hello---" |
| zfill() | 右對齊(數值專用) | 左側(0填充) | "00000hello" |
import unicodedata
def display_ljust(s, width, fillchar=' '):
"""依終端機顯示寬度左對齊(中文/全形算 2)"""
display_w = sum(2 if unicodedata.east_asian_width(c) in 'WF' else 1 for c in s)
if display_w >= width:
return s
pad_count = width - display_w
return s + fillchar * pad_count
print(repr(display_ljust("Hello", 10))) # 'Hello '
print(repr(display_ljust("你好", 10))) # '你好 '(顯示寬度 4,填 6 空格)
print(repr(display_ljust("Hi你好", 10))) # 'Hi你好 '(顯示寬度 6,填 4 空格)
ljust() 是字串左對齊填充的標準方法,語法簡單、行為可預期。關鍵點:不截斷超寬字串、填充字元必須為單一字元、預設空格填充。搭配 rjust()、center()、zfill() 可處理各種對齊需求。終端機顯示對齊涉及中文時,建議自行實作顯示寬度版本。