str.replace(old, new, count=-1) -> str
回傳新字串,將 old 子字串替換為 new。count 指定最大替換次數 (預設 -1 為全部)。
>> 'hello world'.replace('l', 'L')
'heLLo worLd'
>>> 'hello world'.replace('l', 'L', 1)
'heLlo world'
>>> 'hello world'.replace('l', 'L', 2)
'heLLo world'
>>> 'aaa'.replace('aa', 'b')
'ba' # 非重疊匹配:先替換前兩個 a
>>> 'abababa'.replace('aba', 'X')
'XbX' # 非重疊,左至右
>> 'abcDEFghi'.replace('DEF', '')
'abcghi'
>> 'a.b.c.d'.replace('.', '_', 1)
'a_b.c.d'
| 場景 | 推薦方法 | 理由 |
|---|---|---|
| 單一固定子字串替換 | str.replace | C 層實作,極快 |
| 多組固定替換 | str.translate | 一次掃描完成,O(n) |
| 模式替換 (正則) | re.sub | 支援群組、回呼、旗標 |
| 超大字串 (GB 級) 串流替換 | re.sub + 迭代器 / 分塊處理 | 避免載入整字串進記憶體 |
translate 字串? 否,translate 僅支援 1:1 字元映射)
# 多字元替換需用正則或迴圈
# 正則替代 (一次編譯,多次使用)
import re
pattern = re.compile('|'.join(map(re.escape, replacements.keys())))
def multi_replace(text):
return pattern.sub(lambda m: replacements[m.group(0)], text)
print(multi_replace('error: something wrong, debug: value=1'))
# ERROR: something wrong, DBG: value=1
replace 不處理重疊;'aaa'.replace('aa', 'b') → 'ba' 而非 'bb'。re.sub(pattern, repl, flags=re.IGNORECASE)。s.replace('a', 'ab') 會無限增長 (實際只執行一次傳遞,但結果含新 'a' 可能被後續邏輯再處理)。字串不可變,每次 replace 產生新字串。連續多次替換大字串會產生多個中間副本。建議:
translate 或 re.sub。io.StringIO 寫入式建構。replace 是最直觀的字串替換工具,適用於固定子字串、可選限制次數。複雜模式、多組替換、大資料量請改用 re 或 translate。