4

I'm using Python3 and I wonder if there is a module or a default function for converting all characters of a text to html entities (even the letters and digits) because I don't want to make a translation map for this.


Solved: As @justhalf told me, I found the solution by making this function:

def htmlEntities( string ):
    return ''.join(['&#{0};'.format(ord(char)) for char in string])
2
  • Have you done your search in Google to find this? wiki.python.org/moin/EscapingHtml
    – justhalf
    Sep 4, 2013 at 9:16
  • @justhalf: The solution on the Wiki page leaves ASCII codepoints alone; it only gives you entity escapes for non-ASCII characters. The OP (for some unfathomable reason) wants all codepoints escaped.
    – Martijn Pieters
    Sep 4, 2013 at 9:19

1 Answer 1

3

If you want to really escape all characters, there is no default function for that, but you can just replace each character with the ordinals manually:

''.join('&%d;'.format(ord(x)) for x in string)
8
  • sorry, I didn't realize the escaped html gets converted by SO, haha
    – justhalf
    Sep 4, 2013 at 9:21
  • 1
    btw. map(lambda is deprecated, you ought to use ['&%d;' % ord(x) for x in string]
    – vartec
    Sep 4, 2013 at 10:12
  • Doesn't work for me in python3.6. Use html.escape()
    – Claude
    Jul 10, 2017 at 10:00
  • HTMLParser.escape() doesn't exist in any Python version; it has thrown AttributeError: 'HTMLParser' object has no attribute 'escape' from version 3.0 onwards. The html.escape function never escaped anything other than &, <, >, ", and '. Not sure where you got this answer from, but it could never have worked.
    – Martijn Pieters
    Oct 16, 2019 at 21:36
  • 2
    @justhalf: You are pointing to html.parser.HTMLParser.unescape, which indeed exists. I'm talking about the escape() method. unescape() moves from HTML entities to Unicode codepoints, and can be done much more easily with html.unescape() too. You claim that there was an escape() method that would move from Unicode codepoint to HTML entities; this doesn't exist. It never existed. There is the html.escape() function but that doesn't convert non-ascii codepoints to supported HTML5 entities.
    – Martijn Pieters
    Oct 17, 2019 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.