Python ret.sub的使用方法

需求:这里以转义特殊字符串为例
import re

# 替换字符串的映射
map_str = {
    "&": "&",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&#39;",
}

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)

    """
    输出结果:
        &lt;script&gt;alert(1)&lt;/script&gt;
    """
原文地址:https://www.cnblogs.com/ygbh/p/14061514.html