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

Python 字串處理:replace() 方法完整教學與替換策略應用

     編輯:更多程式設計知識

字串替換是文字處理核心操作,Python replace() 方法提供直觀、強大的子字串替換功能:支援全域替換、限制次數、多重替換鏈式呼叫。本文詳細說明語法、參數、行為細節、效能特性與實戰進階模式。

方法語法與說明

str.replace(old, new[, count])
  • old:要被替換的子字串(必須存在,否則無效果)。
  • new:替換後的新子字串(可為空字串,即刪除)。
  • count(選填):最大替換次數,預設 -1 表示全域替換所有出現處。
  • 回傳:新字串(原字串不變)。
  • 關鍵行為:非重疊、從左至右、不支援正則。

實際程式碼範例

#!/usr/bin/python3
# 範例 1:全域替換
s1 = "this is string example....wow!!! this is really string"
print(s1.replace("is", "was"))
# thwas was string example....wow!!! thwas was really string

# 範例 2:限制替換次數
print(s1.replace("is", "was", 3))
# thwas was string example....wow!!! thwas is really string

# 範例 3:刪除子字串(new="")
s2 = "a-b-c-d-e"
print(s2.replace("-", ""))  # abcde

# 範例 4:多重鏈式替換
template = "{greeting}, {name}! Welcome to {place}."
result = (template
    .replace("{greeting}", "Hello")
    .replace("{name}", "Alice")
    .replace("{place}", "Python World"))
print(result)  # Hello, Alice! Welcome to Python World.

# 範例 5:不存在的子字串(無錯誤,回傳原字串)
print("hello".replace("xyz", "abc"))  # hello

# 範例 6:空字串替換(插入字元)
print("abc".replace("", "-"))  # -a-b-c-(每字元間插入,含首尾)

replace() 核心行為深度解析

非重疊替換


s = "aaaa"
print(s.replace("aa", "b"))  # "bb"(非重疊:位置 0-1, 2-3)
# 若為重疊會是 "bab" 或 "bba",但 Python 採非重疊

從左至右、單次掃描


# 替換過的字元不會被再次掃描
s = "aba"
print(s.replace("a", "ab"))  # "abba"(非 "abbba")
# 過程:a→ab, b→b, a→ab → ab + b + ab = abba

count 參數精確控制


s = "is is is is"
print(s.replace("is", "was", 1))  # "was is is is"
print(s.replace("is", "was", 2))  # "was was is is"
print(s.replace("is", "was", 0))  # "is is is is"(0 次 = 無替換)

效能特性

  • 時間複雜度 O(N):單次掃描,C 層實作極快。
  • 記憶體:建立新字串,原字串不變。
  • 大量替換優於迴圈 replace**:單次 replace 優於多次迴圈呼叫。

常見陷阱與避坑指南

  1. 連續替換順序影響結果**:
    
    s = "abc"
    # 先替換 a→b,再 b→c
    print(s.replace("a", "b").replace("b", "c"))  # "ccc"(原 a,b 都變 c)
    
    # 若順序相反
    print(s.replace("b", "c").replace("a", "b"))  # "bcc"(較符合直覺)

    解決:用 str.translate 單次映射,或正則 re.sub 同時替換。

  2. 大小寫敏感**:replace 區分大小寫,不區分需自行 lower() 或用正則 re.IGNORECASE。
  3. 替換空字串插入行為**:"abc".replace("", "-") 產生 -a-b-c-,非預期常導致 Bug。

進階應用模式

1. 模板字串渲染(簡易版)


def render_template(template, **kwargs):
    result = template
    for key, value in kwargs.items():
        result = result.replace("{" + key + "}", str(value))
    return result

print(render_template("Hello {name}, age {age}", name="Bob", age=25))
# Hello Bob, age 25

2. 敏感詞過濾


SENSITIVE_WORDS = ["badword1", "badword2", "secret"]

def filter_text(text, replacement="***"):
    for word in SENSITIVE_WORDS:
        text = text.replace(word, replacement)
    return text

print(filter_text("This contains badword1 and secret info"))
# This contains *** and *** info

3. 路徑分隔符標準化


import os
path = "C:\\Users\\Name\\Documents"
unix_path = path.replace("\\", "/")  # C:/Users/Name/Documents
# 或使用 os.path.normpath

4. 批次替換優化:str.translate


# 單字元多對多替換:translate 單次掃描完成
table = str.maketrans({"a": "@", "e": "3", "i": "1", "o": "0", "s": "$"})
print("leetspeak".translate(table))  # l33t$p3@k

# 多字元批次替換:正則一次完成
import re
replacements = {"cat": "dog", "dog": "cat", "bird": "fish"}
pattern = re.compile("|".join(map(re.escape, replacements.keys())))
result = pattern.sub(lambda m: replacements[m.group()], "cat and dog")
print(result)  # dog and cat(同時替換,避免順序問題)

相關方法比較

方法功能支援正則適用場景
replace()子字串替換否固定字串、高效能、簡單邏輯
re.sub()正則替換是模式匹配、條件替換、複雜邏輯
str.translate()單字元映射否大量單字元替換、最高效能
str.replace() 鏈式多重固定替換否模板渲染、順序不敏感替換

總結

replace() 是字串替換的首選方法:語法簡單、C 層高效能、支援次數限制。關鍵掌握:**非重疊、左至右、單次掃描、大小寫敏感**。複雜替換需求(正則、同時多模式、條件替換)請改用 re.sub;大量單字元映射用 translate。避免連續 replace 順序導致非預期結果,必要時用佔位符中介或正則一次完成。

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