共計 330 個字符,預計需要花費 1 分鐘才能閱讀完成。
可以使用字典來一次替換多個不同的字符串,例如:
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)
這段代碼中,首先定義了一個包含要替換的字符串和對應替換字符串的字典 replace_dict,然后使用 for 循環遍歷字典中的鍵值對,對原始文本進行替換操作,最后打印出替換后的文本。
丸趣 TV 網 – 提供最優質的資源集合!
正文完