Python文字列置換:str.replace()の完全ガイドとその先
Updated on
文字列の置換はテキスト処理で最も頻繁に行われる操作の一つです。ユーザー入力のクリーニング、データ形式の正規化、機密情報の墨消し、テンプレート文字列の変換など、様々な場面で必要になります。Pythonのstr.replace()は単純なケースを1行で処理できますが、大文字小文字を無視したマッチング、正規表現パターン、条件付き置換が必要な場合には力不足です。間違ったツールを選ぶと、単純なタスクを不必要に複雑にするか、複雑なタスクに対して脆いコードを書くことになります。
このガイドでは、Pythonでの文字列置換のすべてのアプローチをカバーします -- 基本的なstr.replace()から、正規表現を使ったre.sub()、文字レベルのtranslate()、そして実世界のテキスト処理のための実践的なパターンまで。
str.replace(old, new, count)
最もシンプルで一般的なメソッドです。oldのすべての出現をnewに置換します。オプションのcountで置換回数を制限できます。
text = "Hello World, Hello Python, Hello Everyone"
# すべての出現を置換
print(text.replace("Hello", "Hi"))
# Hi World, Hi Python, Hi Everyone
# 最初の2つだけを置換
print(text.replace("Hello", "Hi", 2))
# Hi World, Hi Python, Hello Everyone
# 部分文字列を削除(空文字列で置換)
messy = " extra spaces here "
print(messy.replace(" ", ""))
# extraspaceshere主な動作
- 新しい文字列を返します(Pythonでは文字列は不変です)
- デフォルトでは大文字小文字を区別します
countが指定されない限り、すべての出現を置換しますoldが見つからない場合、元の文字列をそのまま返します
original = "Python is great"
new = original.replace("great", "awesome")
print(original) # Python is great(変更なし)
print(new) # Python is awesome大文字小文字を無視した置換
str.replace()は常に大文字小文字を区別します。大文字小文字を無視した置換には、re.sub()とre.IGNORECASEフラグを使用します。
import re
text = "Python is Great, python is Fun, PYTHON is Everywhere"
# 大文字小文字を無視した置換
result = re.sub(r'python', 'Java', text, flags=re.IGNORECASE)
print(result)
# Java is Great, Java is Fun, Java is Everywherere.sub()を使った正規表現置換
re.sub(pattern, replacement, string, count, flags)は正規表現パターンのマッチを置換します。
import re
# 数字を'#'に置換
text = "Call 555-1234 or 555-5678"
print(re.sub(r'\d', '#', text))
# Call ###-#### or ###-####
# 電話番号全体を置換
print(re.sub(r'\d{3}-\d{4}', '[墨消し]', text))
# Call [墨消し] or [墨消し]
# 複数の空白を1つのスペースに置換
messy = "too many spaces here"
print(re.sub(r'\s+', ' ', messy))
# too many spaces hereキャプチャグループの使用
import re
# 姓と名を入れ替える
names = "Smith, John\nDoe, Jane\nBrown, Bob"
swapped = re.sub(r'(\w+), (\w+)', r'\2 \1', names)
print(swapped)
# John Smith
# Jane Doe
# Bob Brown
# 日付にフォーマットを追加
dates = "Meeting on 2026-02-10 and 2026-03-15"
formatted = re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', dates)
print(formatted)
# Meeting on 02/10/2026 and 03/15/2026動的置換のための関数の使用
条件付き置換には文字列の代わりに関数を渡します:
import re
def censor_word(match):
word = match.group()
return word[0] + '*' * (len(word) - 1)
text = "The password is secret and the code is hidden"
censored = re.sub(r'secret|hidden', censor_word, text)
print(censored)
# The password is s***** and the code is h*****import re
# 特定の単語だけをタイトルケースに変換
def smart_capitalize(match):
word = match.group()
minor_words = {'a', 'an', 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to'}
if word.lower() in minor_words:
return word.lower()
return word.capitalize()
title = "the quick BROWN fox AND the lazy DOG"
result = re.sub(r'\b\w+\b', smart_capitalize, title)
print(result)
# the Quick Brown Fox and the Lazy Dog複数置換
replace()の連鎖呼び出し
text = "Hello World! How are you?"
result = text.replace("Hello", "Hi").replace("World", "Earth").replace("you", "they")
print(result) # Hi Earth! How are they?辞書ベースの置換
多数の置換には、辞書とre.sub()を使用します:
import re
def multi_replace(text, replacements):
"""辞書を使用して複数の部分文字列を置換する。"""
pattern = re.compile('|'.join(re.escape(k) for k in replacements))
return pattern.sub(lambda m: replacements[m.group()], text)
text = "The cat sat on the mat with another cat"
replacements = {
'cat': 'dog',
'mat': 'rug',
'sat': 'stood',
}
print(multi_replace(text, replacements))
# The dog stood on the rug with another dogtranslate()を使った文字レベルの置換
個々の文字を置換するには、str.translate()とstr.maketrans()が最速のオプションです:
# 文字を置換: a->@, e->3, o->0
table = str.maketrans('aeo', '@30')
text = "Hello World"
print(text.translate(table))
# H3ll0 W0rld
# 特定の文字を削除
remove_vowels = str.maketrans('', '', 'aeiouAEIOU')
print("Hello World".translate(remove_vowels))
# Hll Wrld
# 1回の呼び出しで置換と削除
table = str.maketrans({'a': '@', 'e': '3', ' ': None})
print("apple pie".translate(table))
# @ppl3pi3メソッド比較
| メソッド | 最適な用途 | 正規表現 | 速度 | 柔軟性 |
|---|---|---|---|---|
str.replace() | シンプルなリテラル置換 | なし | 最速 | 低い |
re.sub() | パターンマッチング、複雑なルール | あり | 中程度 | 最高 |
str.translate() | 単一文字のマッピング | なし | 非常に速い | 低い |
連鎖 .replace() | 少数のリテラル置換 | なし | 速い | 低い |
Dict + re.sub() | 多数の同時置換 | あり | 中程度 | 高い |
実践的な例
テキストのクリーニングと正規化
import re
def clean_text(text):
"""処理のためにテキストを正規化する。"""
text = text.strip()
text = re.sub(r'\s+', ' ', text) # 空白を縮小
text = re.sub(r'[^\w\s.,!?-]', '', text) # 特殊文字を削除
text = text.lower()
return text
raw = " Hello!!! This is MESSY @#$ text... "
print(clean_text(raw))
# hello!!! this is messy text...テンプレート文字列の置換
template = "Dear {name}, your order #{order_id} ships on {date}."
data = {
'name': 'Alice',
'order_id': '12345',
'date': 'Feb 15, 2026',
}
# str.format_mapを使用(手動置換より優れている)
result = template.format_map(data)
print(result)
# Dear Alice, your order #12345 ships on Feb 15, 2026.機密データの墨消し
import re
def redact_pii(text):
"""メール、電話番号、SSNを墨消しする。"""
text = re.sub(r'\b[\w.]+@[\w.]+\.\w+\b', '[メール]', text)
text = re.sub(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', '[電話番号]', text)
text = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[SSN]', text)
return text
msg = "Contact john@example.com or call 555-123-4567. SSN: 123-45-6789"
print(redact_pii(msg))
# Contact [メール] or call [電話番号]. SSN: [SSN]Jupyterでのテキストデータ処理
テキストのクリーニングと変換は反復的な作業です -- サンプルデータに対してパターンをテストし、正規表現を調整し、結果を検証します。RunCell (opens in a new tab)はJupyter用のAIエージェントで、テキスト処理パイプラインをインタラクティブに構築・デバッグし、実際のデータに対して置換パターンをリアルタイムでテストすることができます。
FAQ
Pythonで部分文字列を置換するには?
シンプルな置換にはstr.replace(old, new)を使います:"hello world".replace("world", "python")は"hello python"を返します。これはすべての出現を置換します。3番目の引数を追加して置換回数を制限できます:text.replace("a", "b", 2)は最初の2つのマッチだけを置換します。
Pythonで大文字小文字を無視した置換をするには?
re.sub()とre.IGNORECASEフラグを使用します:re.sub(r'python', 'Java', text, flags=re.IGNORECASE)。組み込みのstr.replace()メソッドは大文字小文字を無視したマッチングをサポートしていません。
複数の異なる文字列を一度に置換するには?
置換の辞書から正規表現パターンを構築します:すべてのキーにマッチするコンパイル済みパターンを作成し、ラムダを使用して各マッチの置換を検索します。あるいは、少数のリテラル置換には.replace()の呼び出しを連鎖させます。
str.replace()とre.sub()の違いは?
str.replace()はリテラルの文字列マッチングのみを行います -- より高速でシンプルです。re.sub()は正規表現を使用し、パターンマッチング、キャプチャグループ、後方参照、関数ベースの置換をサポートします。シンプルなリテラル交換にはstr.replace()を、パターンの柔軟性が必要な場合はre.sub()を使用してください。
Pythonで文字列から文字を削除するには?
3つのアプローチがあります:str.replace(char, "")は特定の部分文字列のすべての出現を削除します。str.translate(str.maketrans("", "", chars))は指定された文字をすべて効率的に削除します。re.sub(r"[pattern]", "", text)は正規表現パターンにマッチする文字を削除します。
まとめ
Pythonは文字列置換のための複数のツールを提供しており、それぞれ異なる複雑さのレベルに適しています。シンプルなリテラル交換にはstr.replace()を、パターンマッチングと複雑なルールにはre.sub()を、高速な文字レベルのマッピングにはstr.translate()を使用してください。複数の同時置換には、辞書駆動のre.sub()アプローチがコードをクリーンで保守しやすく保ちます。