Skip to main content
 首页 » 编程设计

python之如何在 Python 中进行 HTML 转义

2025年05月04日14mengfanrong

<分区>

我正在尝试实现一个替换以下值的函数:

# > with &gt; 
# < with &lt; 
# " with &quot; 
# & with &amp 

我的函数总是出错。到底哪里出了问题?

def escape_html(s): 
    data = list(s) 
    if ">" in data: 
        data.replace(">","&gt;")  
    if "<" in data: 
        data.replace("<","&lt;")  
    if '"' in data: 
        data.replace('"',"&quot;")  
    if "&" in data: 
        data.replace("&","&amp;")  
    word = data.join() 
    return word 
 
print escape_html("<>") 

注意:这更像是一个基本的编程问题。我的重点是我的功能不起作用的原因。我不能为这个项目使用外部库。