Python replace() 字串取代

replace() 方法用來將字串中的指定子字串替換成另一個字串。

基本用法

text = "Hello World"
result = text.replace("World", "Python")
print(result)  # Hello Python

語法

str.replace(old, new, count=-1)
  • old:要被替換的子字串
  • new:替換後的字串
  • count:最大替換次數,-1 表示全部替換(預設)

替換所有出現的子字串

text = "apple apple apple"
result = text.replace("apple", "orange")
print(result)  # orange orange orange

限制替換次數

text = "apple apple apple apple"

print(text.replace("apple", "orange", 1))  # orange apple apple apple
print(text.replace("apple", "orange", 2))  # orange orange apple apple
print(text.replace("apple", "orange", 3))  # orange orange orange apple

刪除子字串

將子字串替換為空字串:

text = "Hello, World!"
result = text.replace(",", "")
print(result)  # Hello World!

# 移除所有空格
text = "Hello World Python"
result = text.replace(" ", "")
print(result)  # HelloWorldPython

字串是不可變的

replace() 會回傳新的字串,原字串不會被修改:

text = "Hello World"
result = text.replace("World", "Python")

print(text)    # Hello World(原字串不變)
print(result)  # Hello Python

大小寫敏感

replace() 是大小寫敏感的:

text = "Hello hello HELLO"
result = text.replace("hello", "hi")
print(result)  # Hello hi HELLO

不區分大小寫的替換

import re

text = "Hello hello HELLO"
result = re.sub("hello", "hi", text, flags=re.IGNORECASE)
print(result)  # hi hi hi

鏈式呼叫

可以連續呼叫多個 replace()

text = "Hello, World!"
result = text.replace("Hello", "Hi").replace("World", "Python").replace("!", "?")
print(result)  # Hi, Python?

實際範例

清理資料

# 移除特殊字元
text = "Hello! How are you? I'm fine."
clean = text.replace("!", "").replace("?", "").replace("'", "")
print(clean)  # Hello How are you Im fine.

# 統一換行符號
text = "Line1\r\nLine2\rLine3\nLine4"
result = text.replace("\r\n", "\n").replace("\r", "\n")
print(result.split("\n"))  # ['Line1', 'Line2', 'Line3', 'Line4']

格式化電話號碼

phone = "0912-345-678"
clean_phone = phone.replace("-", "")
print(clean_phone)  # 0912345678

# 反過來格式化
phone = "0912345678"
formatted = f"{phone[:4]}-{phone[4:7]}-{phone[7:]}"
print(formatted)  # 0912-345-678

模板替換

template = "Dear {name}, your order #{order_id} has been shipped."

message = template.replace("{name}", "Alice").replace("{order_id}", "12345")
print(message)  # Dear Alice, your order #12345 has been shipped.

處理 HTML 特殊字元

def escape_html(text):
    return (text
        .replace("&", "&")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
        .replace("'", "&#39;"))

html = '<script>alert("XSS")</script>'
safe = escape_html(html)
print(safe)  # &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;

使用字典進行多重替換

def multi_replace(text, replacements):
    for old, new in replacements.items():
        text = text.replace(old, new)
    return text

text = "I love apples and bananas"
replacements = {
    "apples": "oranges",
    "bananas": "grapes"
}

result = multi_replace(text, replacements)
print(result)  # I love oranges and grapes

translate() 方法

對於單字元替換,translate() 效率更高:

# 建立轉換表
table = str.maketrans("aeiou", "12345")

text = "hello world"
result = text.translate(table)
print(result)  # h2ll4 w4rld

# 刪除字元
table = str.maketrans("", "", "aeiou")
result = text.translate(table)
print(result)  # hll wrld

使用正規表達式

對於複雜的替換需求,可以使用 re.sub()

import re

# 替換多個空格為單一空格
text = "Hello    World   Python"
result = re.sub(r"\s+", " ", text)
print(result)  # Hello World Python

# 替換數字
text = "Order 123 and Order 456"
result = re.sub(r"\d+", "XXX", text)
print(result)  # Order XXX and Order XXX