How can I percent-encode URL parameters in Python?
A percent-encode URL parameter in Python can be handled via urllib.parse.quote. For transforming spaces into +, go ahead with urllib.parse.quote_plus.
-
Encoding with
quote: -
Encoding with
quote_plus:
Managing Python versions & Unicode characters
Rely on Python 3 for an optimized experience with percent-encoding, as it accommodates Unicode handling. While you had to encode Unicode characters to UTF-8 in Python 2 (Oh, the good ol' times),Python 3 handles this like a boss.👩💼
-
Python 2: Encoding = Extra cash💰:
-
Python 3: Native = Life's easy peasy 🥂:
Empower safe parameter in quote while handling slashes '/'. Default it corresponds to '/', hence, won't encode
The 'Safe' guide
It's high time we understood about safe which is default '/' while percent-encoding:
- The untouchables:
[A-Za-z],[0-9], and'_.-~'are exempted from percent-encoding. - Default
safelinks to '/'. To encode, trysafe=''. - Embrace
quote_plusfor encoding spaces as '+', unlike ' '* encoded as **%20`* by quote.
Exploit urllib.parse.urlencode
When it comes to dealing with query string coupling multiple parameters, use urllib.parse.urlencode. It's your friend to build the query portion of a URL:
This transforms dictionaries encoding both the keys and values, delivering a URL query.
Try alternative libraries
Python's urllib is the textbook for URL encoding. However, feel free to use other options for an enriched experience using external libraries or framework:
-
requestslibrary: -
Django framework:
The art of decoding URLs
There are times when you might need to revert transformation, i.e., decode percent-encoded URLs. Pythons's urllib.parse.unquote is here for the rescue:
Extract maximum from the docs
Make the most out of Python 3 urllib.parse documentation for everything about URL handling. A treasure of descriptions, syntax, and nuances, it can solve every use case that comes your way.
Was this article helpful?