我正在尝试实现一个替换以下值的函数:
# > with >
# < with <
# " with "
# & with &
Run Code Online (Sandbox Code Playgroud)
我的功能一直出错.究竟出了什么问题?
def escape_html(s):
data = list(s)
if ">" in data:
data.replace(">",">")
if "<" in data:
data.replace("<","<")
if '"' in data:
data.replace('"',""")
if "&" in data:
data.replace("&","&")
word = data.join()
return word
print escape_html("<>")
Run Code Online (Sandbox Code Playgroud)
注意:这更像是一个基本的编程问题.我的重点是我的功能不起作用的原因.我不能在这个项目中使用外部库.
用途cgi.escape:
>>> import cgi
>>> cgi.escape('<this & that>')
'<this & that>'
Run Code Online (Sandbox Code Playgroud)
如果您使用Python 3.2+,请使用html.escape文档建议:
cgi.escape因为版本不推荐使用3.2:此功能是不安全的,因为
quote是false在默认情况下,因此不推荐使用.请html.escape()改用.