首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 字串處理:ljust() 方法完整教學與左對齊填充應用

     編輯:更多程式設計知識

字串左對齊並填充至指定寬度是報表輸出、日誌格式化、CLI 介面對齊的常見需求。Python ljust() 方法提供簡潔解法:回傳原字串靠左、右側以指定字元填充至目標寬度的新字串。本文詳細說明語法、參數、行為細節與實戰應用。

方法語法與說明

str.ljust(width[, fillchar])
  • 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    '

實務應用場景

1. 表格欄位對齊

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)

2. 日誌固定寬度欄位

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

3. CLI 選單對齊

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"

進階技巧:顯示寬度對齊(中文算 2)


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() 可處理各種對齊需求。終端機顯示對齊涉及中文時,建議自行實作顯示寬度版本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved