Python替换内容的核心方法是使用字符串的replace()方法,适用于简单文本替换;正则表达式re.sub()可处理复杂规则;文件内容替换需结合读写操作。以下是具体实现方式:
-
字符串替换
使用str.replace(old, new)
直接替换:pythonCopy Code
text = "Hello World" new_text = text.replace("World", "Python") # 输出"Hello Python"
支持多次替换和指定次数:
text.replace("a", "b", 2)
# 仅替换前两次 -
正则表达式替换
通过re.sub(pattern, repl, string)
实现模式匹配替换:pythonCopy Code
import re text = "日期:2023-01-01" result = re.sub(r"\d{4}-\d{2}-\d{2}", "2025-05-06", text) # 替换日期格式
支持分组引用:
re.sub(r"(\d+)", r"编号\1", text)
-
文件内容替换
分三步操作:读取→替换→写入pythonCopy Code
with open("file.txt", "r") as f: content = f.read() new_content = content.replace("旧内容", "新内容") with open("file.txt", "w") as f: f.write(new_content)
大文件建议逐行处理避免内存溢出
-
批量替换字典映射
使用字典+循环实现多组替换:pythonCopy Code
replace_dict = {"旧词1":"新词1", "旧词2":"新词2"} for old, new in replace_dict.items(): text = text.replace(old, new)
注意:替换敏感内容时建议先备份数据,正则表达式需测试边界情况。处理编码问题可添加encoding="utf-8"
参数。