Is there a client-side alternative to html.escape()?

What I’m trying to do:
Escape some user-supplied text, for display as HTML.

What I’ve tried and what’s not working:
Code Sample:

import html  # for std lib html.escape()

If there’s something handy, standard, pre-written and debugged, that would be the obvious choice. If not, I’ll roll my own.

Edit:
I threw this together, in case anyone else needs it:

def html_escape(s: str) -> str:
    """Convert a regular string to HTML-safe format,
    just in case it contains special characters
    """
    result = s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
    result = result.replace('"', '&quot;').replace("'", '&apos;')
    return result
1 Like

That roughly matches the standard library code: cpython/__init__.py at 3.7 · python/cpython · GitHub

2 Likes