Last active
July 4, 2022 08:08
-
-
Save shtrom/d0215c58faa1c626deadeec37fb8a443 to your computer and use it in GitHub Desktop.
urlencode, and escape as html entities, all characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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>') | |
'<script>console.log("hello")</script>' | |
>>> 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