字串右對齊並填充至指定寬度是數值格式化、報表對齊、CLI 介面的常見需求。Python rjust() 方法回傳新字串,原字串靠右、左側以指定字元填充至目標寬度。本文詳細說明語法、參數、與 ljust/center/zfill 差異、實戰應用與進階顯示寬度對齊。
str.rjust(width[, fillchar])
' ',**必須為單一字元**。width <= len(str),直接回傳原字串(不截斷)。#!/usr/bin/python3
# 範例 1:基本右對齊(空格填充)
s = "hello"
print(repr(s.rjust(10))) # ' hello'
print(f"|{s.rjust(10)}|") # | hello|
# 範例 2:自訂填充字元
print(repr(s.rjust(10, '0'))) # '00000hello'
print(repr(s.rjust(10, '-'))) # '-----hello'
print(repr(s.rjust(10, '*'))) # '*****hello'
# 範例 3:寬度小於等於字串長度(不截斷)
print(repr(s.rjust(3))) # 'hello'
print(repr(s.rjust(5))) # 'hello'
# 範例 4:數值字串右對齊(財務報表常用)
numbers = ["123", "4567", "89", "10000"]
for n in numbers:
print(f"{n.rjust(8)}") # 右對齊寬度 8
# 範例 5:中文字串(每字算 1 寬度)
c = "你好"
print(repr(c.rjust(6))) # ' 你好'
print(repr(c.rjust(6, '·'))) # '····你好'
# 錯誤:填充字元長度不為 1
try:
"a".rjust(5, "ab")
except TypeError as e:
print(e) # The fill character must be exactly one character long
# 正確:單一字元(含全形、Emoji)
"a".rjust(5, "あ") # 'あああa'
"a".rjust(5, "😀") # '😀😀😀😀a'
| 方法 | 對齊 | 填充側 | 範例 (w=10, fill='-') | 典型用途 |
|---|---|---|---|---|
| ljust() | 左 | 右 | hello----- | 文字欄位、左對齊表格 |
| rjust() | 右 | 左 | -----hello | 數值欄位、貨幣、編號 |
| center() | 中 | 兩側 | --hello--- | 標題、置中顯示 |
| zfill() | 右 | 左(0) | 00000hello | 數值零填充、編號補零 |
# zfill 自動處理正負號
print("123".zfill(6)) # 000123
print("-123".zfill(6)) # -00123(符號保留在最左)
print("+123".zfill(6)) # +00123
# rjust 不處理符號
print("-123".rjust(6, '0')) # 00-123(符號被推右)
items = [
("收入", 1234567),
("支出", 98765),
("淨利", 1137902),
]
print(f"{'項目':<8} {'金額':>12}")
print("-" * 22)
for name, amt in items:
# 千分位格式 + 右對齊
formatted = f"{amt:>,}".rjust(12)
print(f"{name:<8} {formatted}")
# 輸出:
# 項目 金額
# ----------------------
# 收入 1,234,567
# 支出 98,765
# 淨利 1,137,902
# 產生 001, 002... 格式
for i in range(1, 11):
print(str(i).zfill(3)) # 001, 002... 010
# 或用 rjust
for i in range(1, 11):
print(str(i).rjust(3, '0'))
commands = [
("h", "顯示說明"),
("help", "顯示詳細說明"),
("q", "離開"),
("quit", "退出程式"),
]
max_len = max(len(c[0]) for c in commands)
for cmd, desc in commands:
print(f" {cmd.rjust(max_len)} {desc}")
# h 顯示說明
# help 顯示詳細說明
# q 離開
# quit 退出程式
def progress_bar(current, total, width=20):
filled = int(width * current / total)
bar = "█" * filled + " " * (width - filled)
pct = f"{current*100/total:>5.1f}%"
return f"[{bar}] {pct}"
for i in range(0, 101, 10):
print(f"\r{progress_bar(i, 100)}", end="", flush=True)
time.sleep(0.1)
print()
import unicodedata
def display_rjust(s, width, fillchar=' '):
"""依終端機顯示寬度右對齊"""
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 fillchar * pad_count + s
print(repr(display_rjust("Hello", 10))) # ' Hello'
print(repr(display_rjust("你好", 10))) # ' 你好'(顯示寬 4,填 6)
print(repr(display_rjust("Hi你好", 10))) # ' Hi你好'(顯示寬 6,填 4)
# f-string / format 內建對齊
s = "hello"
print(f"{s:>10}") # ' hello' (右對齊)
print(f"{s:<10}") # 'hello ' (左對齊)
print(f"{s:^10}") # ' hello ' (置中)
print(f"{s:0>10}") # '00000hello' (零填充右對齊)
print(f"{s:*^10}") # '**hello***' (星號置中)
# 數值專用
num = 1234
print(f"{num:>10,}") # ' 1,234' (千分位+右對齊)
print(f"{num:0>10}") # '0000001234'
rjust() 是字串右對齊填充的標準方法,**不截斷超寬字串**、**填充字元必須單一字元**、**預設空格**。數值零填充優先用 zfill() 或格式化字串 f\"{num:0>10}\"。現代 Python 建議優先使用 f-string 格式化,功能更強(千分位、正負號處理、置中、自訂填充字元一次滿足)。理解四大對齊方法差異、顯示寬度與字元數差異,能產出專業級的文字報表與介面。