扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

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

扬州沐宇科技
2024-04-02 14:09:01
python

可以使用字典来一次替换多个不同的字符串,例如:

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循环遍历字典中的键值对,对原始文本进行替换操作,最后打印出替换后的文本。

扫码添加客服微信