【Python入門】replace()で文字列を置換する方法|基本から応用テクまで徹底解説!

python

「文字列の一部を別の言葉に変えたい」「URLの一部を置き換えたい」「NGワードをマスクしたい」

こんなときに便利なのが、Pythonのreplace()メソッドです。

よくある使用場面:

  • テキストデータの清理・前処理
  • 設定ファイルの値の更新
  • HTMLテンプレートでの動的置換
  • ログファイルの機密情報マスキング
  • CSVデータの文字化け修正

他の方法との比較:

# 従来の方法(面倒)
text = "I love JavaScript"
words = text.split()
for i, word in enumerate(words):
    if word == "JavaScript":
        words[i] = "Python"
result = " ".join(words)

# replace()なら1行
result = text.replace("JavaScript", "Python")

replace()を使えば、対象の文字列を簡単に別の文字に置き換えることができ、メール本文、ファイル名、HTMLタグの処理など、幅広い場面で活躍します。

この記事では、replace()の基本構文、使い方、複数置換、よくある注意点を初心者向けにやさしく解説します。

スポンサーリンク

第1章:replace()の基本的な使い方

基本構文

文字列.replace(old, new)

文字列.replace(old, new, count)

パラメータの説明:

  • old:置換対象の文字列
  • new:置換後の文字列
  • count(省略可):置換する回数の上限

基本的な使用例

# 基本的な置換
text = "I love JavaScript"
new_text = text.replace("JavaScript", "Python")
print(new_text)  # I love Python

# 数値の置換
price = "商品価格:1000円"
new_price = price.replace("1000", "1500")
print(new_price)  # 商品価格:1500円

# 記号の置換
date = "2024/05/23"
iso_date = date.replace("/", "-")
print(iso_date)  # 2024-05-23

重要な特徴

1. 元の文字列は変更されない(イミュータブル)

original = "Hello World"
modified = original.replace("World", "Python")

print(original)  # Hello World (変わらない)
print(modified)  # Hello Python (新しい文字列)

2. 大文字・小文字を区別する

text = "Hello hello HELLO"
result = text.replace("hello", "hi")
print(result)  # Hello hi HELLO (小文字のhelloのみ置換)

3. 該当する文字列がすべて置換される

text = "apple apple apple"
result = text.replace("apple", "orange")
print(result)  # orange orange orange (すべて置換)

第2章:実用例とreplaceの応用テクニック

1. 回数を指定した部分置換

# 最初のN回のみ置換
text = "apple apple apple apple"

# 最初の1回のみ
result1 = text.replace("apple", "orange", 1)
print(result1)  # orange apple apple apple

# 最初の2回のみ
result2 = text.replace("apple", "orange", 2)
print(result2)  # orange orange apple apple

# すべて(デフォルト)
result3 = text.replace("apple", "orange")
print(result3)  # orange orange orange orange

2. 文字列の削除(空文字に置換)

# 不要な文字の削除
text = "Hello, World!"
no_comma = text.replace(",", "")
print(no_comma)  # Hello World!

# 空白の削除
text = "a b c d e"
no_spaces = text.replace(" ", "")
print(no_spaces)  # abcde

# 改行文字の削除
multiline = "行1\n行2\n行3"
single_line = multiline.replace("\n", " ")
print(single_line)  # 行1 行2 行3

3. HTMLタグの処理

# HTMLタグの削除(簡易版)
html_text = "<p>こんにちは</p><br><strong>強調</strong>"
clean_text = html_text.replace("<p>", "").replace("</p>", "")
clean_text = clean_text.replace("<br>", "\n")
clean_text = clean_text.replace("<strong>", "").replace("</strong>", "")
print(clean_text)  # こんにちは\n強調

# HTMLエンティティの変換
encoded_text = "&lt;script&gt;alert('Hello')&lt;/script&gt;"
decoded_text = encoded_text.replace("&lt;", "<").replace("&gt;", ">")
print(decoded_text)  # <script>alert('Hello')</script>

4. ファイルパスの変換

# Windows → Unix パス変換
windows_path = "C:\\Users\\Documents\\file.txt"
unix_path = windows_path.replace("\\", "/")
print(unix_path)  # C:/Users/Documents/file.txt

# ファイル拡張子の変更
filename = "document.txt"
new_filename = filename.replace(".txt", ".pdf")
print(new_filename)  # document.pdf

# フォルダ名の一括変更
paths = [
    "/old_project/src/main.py",
    "/old_project/tests/test.py",
    "/old_project/docs/readme.md"
]

new_paths = [path.replace("old_project", "new_project") for path in paths]
for path in new_paths:
    print(path)
# /new_project/src/main.py
# /new_project/tests/test.py
# /new_project/docs/readme.md

5. データクリーニング

# CSVデータの前処理
csv_line = '"Apple, Inc.",  123.45,  "Technology"  '

# 余分な空白を削除
cleaned = csv_line.replace("  ", " ").replace(" ,", ",")
print(cleaned)  # "Apple, Inc.", 123.45, "Technology" 

# 特殊文字の正規化
messy_text = "Hello…world—test"
normalized = messy_text.replace("…", "...").replace("—", "-")
print(normalized)  # Hello...world-test

# 全角・半角変換
mixed_text = "123ABC"
# 注意:これは基本例。実際には専用ライブラリ(jaconv等)を推奨

第3章:複数キーワードを一括で置換する方法

辞書とfor文を使った方法

def replace_multiple(text, replacements):
    """複数の置換を一度に実行"""
    for old, new in replacements.items():
        text = text.replace(old, new)
    return text

# 使用例1:プログラミング言語の置換
text = "Python is easy and Python is powerful"
replacements = {
    "Python": "Java",
    "easy": "simple",
    "powerful": "robust"
}

result = replace_multiple(text, replacements)
print(result)  # Java is simple and Java is robust

# 使用例2:NGワードのマスキング
comment = "この商品は最悪で、詐欺だと思います"
ng_words = {
    "最悪": "***",
    "詐欺": "***"
}

masked_comment = replace_multiple(comment, ng_words)
print(masked_comment)  # この商品は***で、***だと思います

チェーンメソッドによる連続置換

# メソッドチェーンでの連続置換
text = "Hello, World! This is a test."
result = (text
          .replace("Hello", "Hi")
          .replace("World", "Python")
          .replace("test", "example"))
print(result)  # Hi, Python! This is a example.

# 関数として定義
def clean_text(text):
    """テキストの標準化処理"""
    return (text
            .replace("\r\n", "\n")    # 改行コードの統一
            .replace("\r", "\n")
            .replace("\t", "    ")     # タブを空白に
            .replace(" ", " ")        # 全角空白を半角に
            .replace("'", "'")         # クォート記号の統一
            .replace(""", '"')
            .replace(""", '"'))

# 使用例
messy_text = "Hello\tWorld "sample" text"
cleaned = clean_text(messy_text)
print(repr(cleaned))  # 'Hello    World "sample" text'

より高度な置換:正規表現を使った方法

import re

# 電話番号のマスキング
text = "連絡先:090-1234-5678、予備:080-9876-5432"
masked = re.sub(r'\d{3}-\d{4}-\d{4}', 'XXX-XXXX-XXXX', text)
print(masked)  # 連絡先:XXX-XXXX-XXXX、予備:XXX-XXXX-XXXX

# URLの置換
text = "詳細は https://example.com/page を参照してください"
updated = re.sub(r'https?://[^\s]+', '[リンク]', text)
print(updated)  # 詳細は [リンク] を参照してください

# 日付形式の変換
text = "開始日:2024/05/23、終了日:2024/12/31"
converted = re.sub(r'(\d{4})/(\d{2})/(\d{2})', r'\1-\2-\3', text)
print(converted)  # 開始日:2024-05-23、終了日:2024-12-31

第4章:replace()でよくある注意点・落とし穴

注意①:元の文字列は変わらない

# よくある間違い
text = "Hello World"
text.replace("World", "Python")  # 戻り値を使わない
print(text)  # Hello World (変わっていない!)

# 正しい方法
text = "Hello World"
text = text.replace("World", "Python")  # 戻り値を代入
print(text)  # Hello Python

# または新しい変数に代入
original = "Hello World"
modified = original.replace("World", "Python")
print(f"元: {original}, 新: {modified}")

注意②:予期しない部分一致

# 部分文字列も置換されてしまう例
text = "I have an apple and a pineapple"
result = text.replace("apple", "orange")
print(result)  # I have an orange and a pineorange

# 対策:正確な単語境界での置換
import re
text = "I have an apple and a pineapple"
result = re.sub(r'\bapple\b', 'orange', text)
print(result)  # I have an orange and a pineapple

注意③:置換順序の影響

# 置換順序が結果に影響する例
text = "abc"

# パターン1
result1 = text.replace("a", "b").replace("b", "c")
print(result1)  # ccc (a→b→c の順)

# パターン2
result2 = text.replace("b", "c").replace("a", "b")
print(result2)  # bcc (b→c→a の順)

# 解決策:一時的な中間文字を使用
def safe_replace_multiple(text, replacements):
    """安全な複数置換"""
    # 一時的なプレースホルダーを使用
    temp_map = {}
    temp_text = text
    
    for i, (old, new) in enumerate(replacements.items()):
        placeholder = f"__TEMP_{i}__"
        temp_map[placeholder] = new
        temp_text = temp_text.replace(old, placeholder)
    
    # プレースホルダーを実際の値に置換
    for placeholder, new_value in temp_map.items():
        temp_text = temp_text.replace(placeholder, new_value)
    
    return temp_text

# 使用例
text = "apple banana apple"
replacements = {"apple": "banana", "banana": "apple"}
result = safe_replace_multiple(text, replacements)
print(result)  # banana apple banana

注意④:大文字・小文字の扱い

# 大文字小文字を区別する
text = "Hello HELLO hello"
result = text.replace("hello", "hi")
print(result)  # Hello HELLO hi (小文字のみ置換)

# 大文字小文字を無視したい場合
def case_insensitive_replace(text, old, new):
    """大文字小文字を無視した置換"""
    import re
    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

# または、lower()を使った方法
def simple_case_insensitive_replace(text, old, new):
    """シンプルな大文字小文字無視置換"""
    # 一時的に小文字にして位置を特定し、元の大文字小文字を保持
    # (完全ではないが、シンプルなケースには有効)
    return text.lower().replace(old.lower(), new)

# ただし、この方法は元の大文字小文字が失われる

注意⑤:空文字列の処理

# 空文字列での置換
text = "Hello World"
result = text.replace("", "X")
print(result)  # XHXeXlXlXoX XWXoXrXlXdX (各文字の間にXが挿入)

# 空文字列への置換(削除)
text = "Hello, World!"
result = text.replace(",", "")
print(result)  # Hello World!

第5章:実用的なreplace()活用パターン

テンプレート文字列の処理

def format_template(template, variables):
    """テンプレート文字列の変数置換"""
    result = template
    for key, value in variables.items():
        placeholder = f"{{{key}}}"  # {key} 形式のプレースホルダー
        result = result.replace(placeholder, str(value))
    return result

# 使用例
email_template = """
件名: {subject}

{customer_name} 様

{message}

{signature}
"""

variables = {
    "subject": "重要なお知らせ",
    "customer_name": "田中",
    "message": "新しいサービスについてご案内いたします。",
    "signature": "株式会社サンプル"
}

formatted_email = format_template(email_template, variables)
print(formatted_email)

設定ファイルの動的生成

def generate_config(template_path, output_path, config_values):
    """設定ファイルの動的生成"""
    # テンプレートファイルの読み込み
    with open(template_path, 'r', encoding='utf-8') as f:
        template = f.read()
    
    # 変数の置換
    config_content = template
    for key, value in config_values.items():
        config_content = config_content.replace(f"{{{{ {key} }}}}", str(value))
    
    # 設定ファイルの書き出し
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(config_content)

# 使用例(ファイルが存在する場合)
# config_values = {
#     "database_host": "localhost",
#     "database_port": "5432",
#     "api_key": "your-api-key"
# }
# generate_config("config.template", "config.ini", config_values)

ログファイルの前処理

def clean_log_data(log_content):
    """ログファイルのクリーニング"""
    # 機密情報のマスキング
    cleaned = log_content
    
    # IPアドレスのマスキング
    import re
    cleaned = re.sub(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', 'XXX.XXX.XXX.XXX', cleaned)
    
    # メールアドレスのマスキング
    cleaned = re.sub(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', 'XXX@XXX.com', cleaned)
    
    # パスワード関連の情報をマスク
    cleaned = cleaned.replace("password=", "password=***")
    cleaned = cleaned.replace("token=", "token=***")
    
    return cleaned

# 使用例
sample_log = """
2024-05-23 10:00:00 INFO User john.doe@example.com logged in from 192.168.1.100
2024-05-23 10:01:00 DEBUG Authentication token=abc123def456 generated
2024-05-23 10:02:00 ERROR Login failed for user test@gmail.com password=secret123
"""

cleaned_log = clean_log_data(sample_log)
print(cleaned_log)

まとめ

replace()は、Pythonで文字列処理をする上で最も使用頻度が高いメソッドの1つです。

ちょっとした変更から大量の一括置換まで、これ1つで対応できます。

本記事の重要ポイント

基本的な使い方:

  • 文字列.replace(old, new) で基本的な置換
  • 文字列.replace(old, new, count) で置換回数を制限
  • 元の文字列は変更されない(新しい文字列が返される)

応用テクニック:

  • 辞書とfor文での複数キーワード一括置換
  • メソッドチェーンでの連続置換
  • 正規表現との組み合わせで高度な置換

注意すべきポイント:

  • 戻り値の代入忘れ:元の文字列は変更されない
  • 部分一致の置換:予期しない置換に注意
  • 置換順序の影響:複数置換時の順序に注意
  • 大文字小文字の区別:必要に応じて工夫が必要

コメント

タイトルとURLをコピーしました