html%3c%3e表示lt,在Python中转义HTML最简单的方法是什么?

本文介绍了两种方法来实现HTML特殊字符转义,包括使用Python的cgi.escape模块和正则表达式。区别在于,正则表达式版本能够处理已经转义的字符,而不会造成重复转义。示例代码详细展示了这两种方法的实现细节,适用于处理包含HTML特殊字符的文本字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不是最简单的方法,但仍然简单。与cgi.escape模块的主要区别 - 如果您的文本中已经有&,它仍然可以正常工作。正如你从评论中看到的那样:

cgi.escape版本

def escape(s, quote=None):

'''Replace special characters "&", "" to HTML-safe sequences.

If the optional flag quote is true, the quotation mark character (")

is also translated.'''

s = s.replace("&", "&") # Must be done first!

s = s.replace("

s = s.replace(">", ">")

if quote:

s = s.replace('"', """)

return s正则表达式版本

QUOTE_PATTERN = r"""([&<>"'])(?!(amp|lt|gt|quot|#39);)"""

def escape(word):

"""

Replaces special characters <>&"' to HTML-safe sequences.

With attention to already escaped characters.

"""

replace_with = {

'

'>': '<',

'&': '&',

'"': '"', # should be escaped in attributes

"'": ''' # should be escaped in attributes

}

quote_pattern = re.compile(QUOTE_PATTERN)

return re.sub(quote_pattern, lambda x: replace_with[x.group(0)], word)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值