UniCoreFW

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&lt;&gt; &amp;&quot;&#39;&#96;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("&amp;") elif ch == "<": out.append("&lt;") elif ch == ">": out.append("&gt;") elif ch == '"': out.append("&quot;") elif ch == "'": out.append("&#39;") elif ch == "`": out.append("&#96;") else: out.append(ch) return "".join(out)