When building URLs in Python, you may occasionally need to encode special characters to ensure they transmit properly. For example, spaces need to be converted to %20 and ampersands to %26. Thankfully, Python's urllib module provides simple ways to handle URL encoding.
Why Encode URLs?
URLs only allow certain alphanumeric characters like letters, numbers, and some symbols such as
For example, an URL with spaces like
www.example.com/path%20with%20spaces
This ensures special characters transmit safely through networks and servers can properly interpret them.
Python's urllib for URL Encoding
Python's
from urllib.parse import urlencode
params = {"name": "John Wick", "category": "Action & Adventure"}
print(urlencode(params))
# name=John+Wick&category=Action+%26+Adventure
We can also manually encode pieces of URLs as needed:
from urllib.parse import quote_plus
url = "http://localhost:8000/movies/" + quote_plus("Science Fiction")
# http://localhost:8000/movies/Science%20Fiction
The
When to Encode URLs
Getting in the habit of encoding URLs ensures your applications handle edge cases safely!
I tried to provide some practical examples on why and how to encode URLs in Python, along with tips on specific methods that can help.