escape()
Escape HTML characters in a string.
Implementation
Args: string: The string to escape (None→""). Returns: An HTML-escaped string, using decimal entities for ' and `.
Example
escape('abc<> &"'`efg')
Expected output: "abc<> &"'`efg"
Source Code
def escape(string: Any) -> str:
if string is None:
return ""
s = str(string)
out: list[str] = []
for ch in s:
if ch == "&":
out.append("&")
elif ch == "<":
out.append("<")
elif ch == ">":
out.append(">")
elif ch == '"':
out.append(""")
elif ch == "'":
out.append("'")
elif ch == "`":
out.append("`")
else:
out.append(ch)
return "".join(out)