Pythonで文字列・数値を右寄せ、中央寄せ、左寄せする方法完全解説
データの表示やレポート作成において、文字列や数値の配置を整えることは重要です。Pythonでは複数の方法で文字列の右寄せ、中央寄せ、左寄せを実現できます。この記事では、f文字列、format()メソッド、文字列メソッドを使った配置方法を詳しく解説します。
目次
f文字列を使った文字配置(推奨)
Python 3.6以降で使用可能なf文字列は、最も読みやすく効率的な文字配置の方法です。
左寄せ(<)
text = "Python"
print(f"'{text:<10}'") # 'Python '
print(f"'{text:<15}'") # 'Python '
# 数値の左寄せ
num = 123
print(f"'{num:<10d}'") # '123 '
右寄せ(>)
text = "Python"
print(f"'{text:>10}'") # ' Python'
print(f"'{text:>15}'") # ' Python'
# 数値の右寄せ
num = 123
print(f"'{num:>10d}'") # ' 123'
中央寄せ(^)
text = "Python"
print(f"'{text:^10}'") # ' Python '
print(f"'{text:^15}'") # ' Python '
# 数値の中央寄せ
num = 123
print(f"'{num:^10d}'") # ' 123 '
任意の文字でパディング
text = "Hello"
print(f"'{text:*<10}'") # 'Hello*****'
print(f"'{text:*>10}'") # '*****Hello'
print(f"'{text:*^10}'") # '**Hello***'
# 数値でも同様
num = 42
print(f"'{num:0>8d}'") # '00000042'
print(f"'{num:-^8d}'") # '---42---'
format()メソッドを使った文字配置
format()メソッドでも同様の配置指定が可能です。
text = "Python"
print("'{:<10}'".format(text)) # 'Python '
print("'{:>10}'".format(text)) # ' Python'
print("'{:^10}'".format(text)) # ' Python '
# パディング文字の指定
print("'{:*^10}'".format(text)) # '**Python**'
文字列メソッドを使った配置
ljust()メソッド(左寄せ)
text = "Hello"
print(f"'{text.ljust(10)}'") # 'Hello '
print(f"'{text.ljust(10, '*')}'") # 'Hello*****'
# 数値を文字列に変換してから適用
num = 123
print(f"'{str(num).ljust(8)}'") # '123 '
rjust()メソッド(右寄せ)
text = "Hello"
print(f"'{text.rjust(10)}'") # ' Hello'
print(f"'{text.rjust(10, '*')}'") # '*****Hello'
# ゼロ埋めの右寄せ
num = 123
print(f"'{str(num).rjust(8, '0')}'") # '00000123'
center()メソッド(中央寄せ)
text = "Hello"
print(f"'{text.center(10)}'") # ' Hello '
print(f"'{text.center(10, '*')}'") # '**Hello***'
# 数値の中央寄せ
num = 123
print(f"'{str(num).center(8)}'") # ' 123 '
数値の小数点揃え
小数点以下の桁数指定と右寄せ
numbers = [3.14, 123.456789, 0.1]
for num in numbers:
print(f"{num:>10.2f}")
# 3.14
# 123.46
# 0.10
通貨表示での右寄せ
prices = [1500, 250, 12000]
for price in prices:
print(f"¥{price:>8,}")
# ¥1,500
# ¥250
# ¥12,000
実用的な応用例
表形式データの整列
students = [
{"name": "田中", "score": 85, "grade": "B"},
{"name": "佐藤", "score": 92, "grade": "A"},
{"name": "山田", "score": 78, "grade": "C"},
]
print(f"{'名前':^6} | {'得点':^4} | {'評価':^2}")
print("-" * 20)
for student in students:
print(f"{student['name']:^6} | {student['score']:^4} | {student['grade']:^2}")
# 名前 | 得点 | 評価
# --------------------
# 田中 | 85 | B
# 佐藤 | 92 | A
# 山田 | 78 | C
レシート風の表示
items = [
{"name": "リンゴ", "price": 150, "qty": 3},
{"name": "バナナ", "price": 200, "qty": 2},
{"name": "オレンジ", "price": 300, "qty": 1},
]
print("=" * 30)
print(f"{'商品名':<10} {'単価':>6} {'数量':>4} {'小計':>6}")
print("-" * 30)
total = 0
for item in items:
subtotal = item['price'] * item['qty']
total += subtotal
print(f"{item['name']:<10} {item['price']:>6} {item['qty']:>4} {subtotal:>6}")
print("-" * 30)
print(f"{'合計':<10} {'':<6} {'':<4} {total:>6}")
print("=" * 30)
# ==============================
# 商品名 単価 数量 小計
# ------------------------------
# リンゴ 150 3 450
# バナナ 200 2 400
# オレンジ 300 1 300
# ------------------------------
# 合計 1150
# ==============================
ログメッセージの整列
import datetime
logs = [
{"time": datetime.datetime.now(), "level": "INFO", "msg": "システム開始"},
{"time": datetime.datetime.now(), "level": "WARNING", "msg": "メモリ使用量が80%を超過"},
{"time": datetime.datetime.now(), "level": "ERROR", "msg": "データベース接続エラー"},
]
for log in logs:
timestamp = log["time"].strftime("%Y-%m-%d %H:%M:%S")
print(f"{timestamp} [{log['level']:^7}] {log['msg']}")
# 2025-08-06 10:30:15 [ INFO ] システム開始
# 2025-08-06 10:30:16 [WARNING] メモリ使用量が80%を超過
# 2025-08-06 10:30:17 [ ERROR ] データベース接続エラー
進行状況バーの表示
def show_progress(current, total, bar_length=20):
progress = current / total
filled_length = int(bar_length * progress)
bar = '█' * filled_length + '-' * (bar_length - filled_length)
percentage = progress * 100
print(f"進行状況: [{bar}] {percentage:>6.1f}% ({current:>3}/{total})")
# 使用例
for i in range(0, 101, 10):
show_progress(i, 100)
# 進行状況: [------------------] 0.0% ( 0/100)
# 進行状況: [██----------------] 10.0% ( 10/100)
# 進行状況: [████--------------] 20.0% ( 20/100)
# ...
# 進行状況: [██████████████████] 100.0% (100/100)
メニュー表示の整列
menu_items = [
{"id": 1, "name": "ハンバーガー", "price": 500},
{"id": 2, "name": "チーズバーガー", "price": 600},
{"id": 3, "name": "フライドポテト", "price": 300},
{"id": 4, "name": "コーラ", "price": 200},
]
print("=" * 40)
print(f"{'番号':^4} | {'メニュー名':^12} | {'価格':^6}")
print("=" * 40)
for item in menu_items:
print(f"{item['id']:^4} | {item['name']:<12} | ¥{item['price']:>4}")
print("=" * 40)
# ========================================
# 番号 | メニュー名 | 価格
# ========================================
# 1 | ハンバーガー | ¥ 500
# 2 | チーズバーガー | ¥ 600
# 3 | フライドポテト | ¥ 300
# 4 | コーラ | ¥ 200
# ========================================
日本語文字列の配置における注意点
日本語などの全角文字は1文字で2バイト分の幅を占めるため、配置が崩れることがあります。
# 問題のある例
japanese_text = "こんにちは"
english_text = "Hello"
print(f"'{japanese_text:>10}'") # ' こんにちは'(実際は位置がずれる)
print(f"'{english_text:>10}'") # ' Hello'
この問題を解決するには、全角文字の幅を考慮したライブラリを使用するか、手動で調整する必要があります。
各方法の特徴と使い分け
f文字列(推奨)
- 利点: 読みやすく高速、豊富な書式指定
- 用途: Python 3.6以降での一般的な用途
format()メソッド
- 利点: 動的な書式指定が可能
- 用途: 書式が実行時に決まる場合
文字列メソッド(ljust, rjust, center)
- 利点: シンプルで直感的
- 用途: 単純な配置のみが必要な場合
まとめ
Pythonでの文字列・数値の配置は、f文字列、format()メソッド、文字列メソッドなど複数の方法があります。現在はf文字列を使用することが推奨されており、左寄せ(<)、右寄せ(>)、中央寄せ(^)の記号を使って直感的に配置を指定できます。
表形式のデータ表示、レシートやログの整形、進行状況の表示など、様々な場面で文字配置は重要な役割を果たします。適切な配置方法を選択することで、読みやすく整理されたアウトプットを生成できるようになります。
■らくらくPython塾 – 読むだけでマスター
■プロンプトだけでオリジナルアプリを開発・公開してみた!!
■AI時代の第一歩!「AI駆動開発コース」はじめました!
テックジム東京本校で先行開始。
■テックジム東京本校
「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。
<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。
<月1開催>放送作家による映像ディレクター養成講座
<オンライン無料>ゼロから始めるPython爆速講座
