Skip to content

Instantly share code, notes, and snippets.

@shtrom
Last active July 4, 2022 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shtrom/d0215c58faa1c626deadeec37fb8a443 to your computer and use it in GitHub Desktop.
Save shtrom/d0215c58faa1c626deadeec37fb8a443 to your computer and use it in GitHub Desktop.
urlencode, and escape as html entities, all characters
def encode_all(string):
'''
From https://gist.github.com/Paradoxis/6336c2eaea20a591dd36bb1f5e227da2 via https://stackoverflow.com/a/67629249/10660788
>>> encode_all('<script>console.log("hello")</script>')
'%3c%73%63%72%69%70%74%3e%63%6f%6e%73%6f%6c%65%2e%6c%6f%67%28%22%68%65%6c%6c%6f%22%29%3c%2f%73%63%72%69%70%74%3e'
'''
return "".join("%{0:0>2}".format(format(ord(char), "x")) for char in string)
def escape_all(string):
''''
>>> escape_all('<script>console.log("hello")</script>')
'&#60&#115&#99&#114&#105&#112&#116&#62&#99&#111&#110&#115&#111&#108&#101&#46&#108&#111&#103&#40&#34&#104&#101&#108&#108&#111&#34&#41&#60&#47&#115&#99&#114&#105&#112&#116&#62'
>>> html.unescape(escape_all('<script>console.log("hello")</script>'))
'<script>console.log("hello")</script>'
''''
return "".join("&#{}".format(ord(char)) for char in string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment