溫馨提示×

Python中怎么用replace()一次替換多個不同的字符串

小億
489
2024-04-02 14:09:01
欄目: 編程語言

可以使用字典來一次替換多個不同的字符串,例如:

text = "Hello World! This is a test."
replace_dict = {"Hello": "Hi", "World": "Earth", "test": "example"}
new_text = text
for old_str, new_str in replace_dict.items():
    new_text = new_text.replace(old_str, new_str)

print(new_text)

這段代碼中,首先定義了一個包含要替換的字符串和對應(yīng)替換字符串的字典replace_dict,然后使用for循環(huán)遍歷字典中的鍵值對,對原始文本進(jìn)行替換操作,最后打印出替換后的文本。

0