Skip to content
Advertisement

Python3 Convert all characters to HTML Entities

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])

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement