python - 如何在 Python 中进行 HTML 转义?

标签 python string

<分区>

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

# > 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("<>")

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

最佳答案

使用cgi.escape :

>>> import cgi
>>> cgi.escape('<this & that>')
'&lt;this &amp; that&gt;'

如果您使用 Python 3.2+,请使用 html.escape如文档所示:

cgi.escape

Deprecated since version 3.2: This function is unsafe because quote is false by default, and therefore deprecated. Use html.escape() instead.

关于python - 如何在 Python 中进行 HTML 转义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20918146/

相关文章:

regex - 如何在 Scala 中识别表情符号?

c++ - 如何确定中间包含 "\0"的 std::string 的长度?

c++ - 如何读取一个文件,反转文本的一部分并将反转的部分写入 C++ 上的另一个文件?

string - char 到 string 转换的所有权问题

javascript - 更改 jQuery 上的唯一字符

python - 使用 Python 处理一个巨大的 CSV 时, 'killed' 是什么意思,突然停止?

python - 如何在 django 中重定向时发送字典或数据?

python - 带有 OpenCV 的 Numpy gradient() 从不为负

python - 使用 Python 下载 Kaggle 数据集

python - 在 Python/Numpy 中优化许多矩阵运算