python批量替换字符串
时间: 2023-11-08 07:05:03 浏览: 148
批量替换字符串
5星 · 资源好评率100%
你可以使用Python的字符串方法replace()来批量替换字符串。replace()方法接受两个参数,第一个参数是要被替换的子字符串,第二个参数是要替换成的新字符串。下面是一个示例代码:
```python
def batch_replace_string(original_string, replacements):
for old_str, new_str in replacements.items():
original_string = original_string.replace(old_str, new_str)
return original_string
replacements = {
"apple": "orange",
"banana": "grape",
"cherry": "melon"
}
original_string = "I like apple, banana, and cherry."
new_string = batch_replace_string(original_string, replacements)
print(new_string)
```
这段代码会将原始字符串中的"apple"替换成"orange","banana"替换成"grape","cherry"替换成"melon",然后输出结果为:"I like orange, grape, and melon."
阅读全文