字串替換是文字處理核心操作,Python replace() 方法提供直觀、強大的子字串替換功能:支援全域替換、限制次數、多重替換鏈式呼叫。本文詳細說明語法、參數、行為細節、效能特性與實戰進階模式。
str.replace(old, new[, count])
#!/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-(每字元間插入,含首尾)
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
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 次 = 無替換)
replace 優於多次迴圈呼叫。
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 同時替換。
replace 區分大小寫,不區分需自行 lower() 或用正則 re.IGNORECASE。"abc".replace("", "-") 產生 -a-b-c-,非預期常導致 Bug。
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
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
import os
path = "C:\\Users\\Name\\Documents"
unix_path = path.replace("\\", "/") # C:/Users/Name/Documents
# 或使用 os.path.normpath
# 單字元多對多替換: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 順序導致非預期結果,必要時用佔位符中介或正則一次完成。