You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

20 lines
647 B

  1. """
  2. General functions for HTML manipulation.
  3. """
  4. _escape_map = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;'}
  5. _escape_map_full = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;',
  6. ord('"'): '&quot;', ord('\''): '&#x27;'}
  7. # NB: this is a candidate for a bytes/string polymorphic interface
  8. def escape(s, quote=True):
  9. """
  10. Replace special characters "&", "<" and ">" to HTML-safe sequences.
  11. If the optional flag quote is true (the default), the quotation mark
  12. character (") is also translated.
  13. """
  14. if quote:
  15. return s.translate(_escape_map_full)
  16. return s.translate(_escape_map)