Python文字列を置換する方法 – replace, translate, re.subの使い分け

 

replace()メソッドによる基本的な置換

最もシンプルな文字列置換方法はreplace()メソッドです。

基本的な置換

# 基本的な文字列置換
text = "Hello World"
new_text = text.replace("World", "Python")
print(new_text)  # Hello Python

# 日本語文字列の置換
message = "今日は良い天気です"
new_message = message.replace("良い", "素晴らしい")
print(new_message)  # 今日は素晴らしい天気です

置換回数の制限

# 置換回数を制限
text = "apple apple apple"
# 最初の1つだけ置換
result1 = text.replace("apple", "orange", 1)
print(result1)  # orange apple apple

# 最初の2つを置換
result2 = text.replace("apple", "orange", 2)
print(result2)  # orange orange apple

複数の置換

def multiple_replace(text, replacements):
    for old, new in replacements.items():
        text = text.replace(old, new)
    return text

# 使用例
text = "赤い車と青い車"
replacements = {"赤い": "黒い", "青い": "白い"}
result = multiple_replace(text, replacements)
print(result)  # 黒い車と白い車

translate()メソッドによる高速置換

文字レベルでの一括置換にはtranslate()メソッドが効率的です。

基本的なtranslate使用

# 文字の変換テーブルを作成
text = "Hello World"
# 'l'を'x'に、'o'を'0'に置換
trans_table = str.maketrans('lo', 'x0')
result = text.translate(trans_table)
print(result)  # Hexx0 W0rxd

文字の削除

# 特定の文字を削除
text = "Hello, World!"
# カンマと感嘆符を削除
trans_table = str.maketrans('', '', ',!')
result = text.translate(trans_table)
print(result)  # Hello World

実用的な例:数字の変換

# 全角数字を半角数字に変換
text = "12345"
trans_table = str.maketrans('1234567890', '1234567890')
result = text.translate(trans_table)
print(result)  # 12345

正規表現による高度な置換

re.sub()の基本使用

import re

# パターンマッチによる置換
text = "今日は2023年12月25日です"
# 数字を「X」に置換
result = re.sub(r'\d+', 'X', text)
print(result)  # 今日はX年X月X日です

# 特定パターンの置換
email = "連絡先: user@example.com"
result = re.sub(r'\S+@\S+', '***@***.***', email)
print(result)  # 連絡先: ***@***.***

キャプチャグループを使った置換

# 日付形式の変更
text = "2023/12/25"
# YYYY/MM/DD を YYYY年MM月DD日 に変換
result = re.sub(r'(\d{4})/(\d{2})/(\d{2})', r'\1年\2月\3日', text)
print(result)  # 2023年12月25日

# 電話番号のフォーマット
phone = "09012345678"
result = re.sub(r'(\d{3})(\d{4})(\d{4})', r'\1-\2-\3', phone)
print(result)  # 090-1234-5678

re.subn()による置換回数取得

# 置換回数も取得
text = "apple apple orange apple"
result, count = re.subn(r'apple', 'banana', text)
print(f"結果: {result}")  # 結果: banana banana orange banana
print(f"置換回数: {count}")  # 置換回数: 3

実用的な活用例

HTMLタグの除去

import re

def remove_html_tags(text):
    # HTMLタグを除去
    clean_text = re.sub(r'<[^>]+>', '', text)
    return clean_text

# 使用例
html_text = "<p>これは<strong>重要</strong>なメッセージです。</p>"
clean = remove_html_tags(html_text)
print(clean)  # これは重要なメッセージです。

敏感情報のマスキング

def mask_sensitive_info(text):
    # 電話番号をマスク
    text = re.sub(r'\d{3}-\d{4}-\d{4}', 'XXX-XXXX-XXXX', text)
    # メールアドレスをマスク
    text = re.sub(r'\S+@\S+\.\S+', '***@***.***', text)
    return text

# 使用例
info = "連絡先: 090-1234-5678, email: user@example.com"
masked = mask_sensitive_info(info)
print(masked)  # 連絡先: XXX-XXXX-XXXX, email: ***@***.***

テキストの正規化

def normalize_text(text):
    # 連続する空白を1つにまとめる
    text = re.sub(r'\s+', ' ', text)
    # 前後の空白を除去
    text = text.strip()
    return text

# 使用例
messy_text = "  これは    テスト   です  "
normalized = normalize_text(messy_text)
print(f"'{normalized}'")  # 'これは テスト です'

パフォーマンス比較と使い分け

各手法の使い分け指針

# 単純な文字列置換: replace()
simple_text = "Hello World"
result1 = simple_text.replace("World", "Python")

# 複数文字の一括変換: translate()
text_with_chars = "Hello123World456"
trans_table = str.maketrans('123456', 'ABCDEF')
result2 = text_with_chars.translate(trans_table)

# パターンマッチ: re.sub()
pattern_text = "価格は1000円、税込み1100円です"
result3 = re.sub(r'\d+', 'XXX', pattern_text)

大文字小文字を無視した置換

import re

def case_insensitive_replace(text, old, new):
    return re.sub(re.escape(old), new, text, flags=re.IGNORECASE)

# 使用例
text = "Hello hello HELLO"
result = case_insensitive_replace(text, "hello", "hi")
print(result)  # hi hi hi

まとめ

Python文字列置換には用途に応じて複数の方法があります。単純な置換にはreplace()、文字レベルの高速変換にはtranslate()、パターンマッチングによる高度な置換にはre.sub()を使い分けることで、効率的で適切な文字列処理が実現できます。

■プロンプトだけでオリジナルアプリを開発・公開してみた!!

■AI時代の第一歩!「AI駆動開発コース」はじめました!

テックジム東京本校で先行開始。

■テックジム東京本校

「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。

<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。

<月1開催>放送作家による映像ディレクター養成講座

<オンライン無料>ゼロから始めるPython爆速講座