需求:这里以转义特殊字符串为例
import re # 替换字符串的映射 map_str = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", } def callback(match): """ 返回替换的结果 """ return map_str.get(match.group(0)) if __name__ == '__main__': src_text = '<script>alert(1)</script>' ret = re.compile("[&<>"']") s = ret.sub(callback, src_text) print(s) """ 输出结果: <script>alert(1)</script> """