>>> urllib.parse.quote_plus("C:\stuff\spam.txt")
'C%3A%5Cstuff%5Cspam.txt'
>>> x = urllib.parse.quote_plus("a & b #! c")
>>> x
'a+%26+b+%23%21+c'
>>> urllib.parse.unquote_plus(x)
'a & b #! c'
URL escape sequences embed the hexadecimal values of nonsafe characters following
a % sign (this is usually their ASCII codes). In urllib.parse, nonsafe characters are
usually taken to include everything except letters, digits, and a handful of safe special
characters (any in '_.-'), but the two tools differ on forward slashes, and you can
extend the set of safe characters by passing an extra string argument to the quote calls
to customize the translations:
>>> urllib.parse.quote_plus("uploads/index.txt")
'uploads%2Findex.txt'
>>> urllib.parse.quote("uploads/index.txt")
'uploads/index.txt'
>>>
>>> urllib.parse.quote_plus("uploads/index.txt", '/')
'uploads/index.txt'
>>> urllib.parse.quote("uploads/index.txt", '/')
'uploads/index.txt'
>>> urllib.parse.quote("uploads/index.txt", '')
'uploads%2Findex.txt'
>>>
>>> urllib.parse.quote_plus("uploads\index.txt")
'uploads%5Cindex.txt'
>>> urllib.parse.quote("uploads\index.txt")
'uploads%5Cindex.txt'
>>> urllib.parse.quote_plus("uploads\index.txt", '\\')
'uploads\\index.txt'
Note that Python’s cgi module also translates URL escape sequences back to their
original characters and changes + signs to spaces during the process of extracting input
information. Internally, cgi.FieldStorage automatically calls urllib.parse tools which
unquote if needed to parse and unescape parameters passed at the end of URLs. The
upshot is that CGI scripts get back the original, unescaped URL strings, and don’t need
to unquote values on their own. As we’ve seen, CGI scripts don’t even need to know
that inputs came from a URL at all.
Escaping URLs Embedded in HTML Code
We’ve seen how to escape text inserted into both HTML and URLs. But what do we
do for URLs inside HTML? That is, how do we escape when we generate and embed
text inside a URL, which is itself embedded inside generated HTML code? Some of our
earlier examples used hardcoded URLs with appended input parameters inside
More on HTML and URL Escapes | 1205