How to Encode URL in Python: Simple Guide with Examples
urllib.parse.quote to encode parts of the URL or urllib.parse.urlencode to encode query parameters. These functions convert special characters into a format safe for URLs.Syntax
urllib.parse.quote(string, safe=''): Encodes a string by replacing special characters with percent-encoded values. The safe parameter lets you specify characters that should not be encoded.
urllib.parse.urlencode(query, doseq=False): Encodes a dictionary or sequence of two-element tuples into a URL query string.
from urllib.parse import quote, urlencode # Encoding a string encoded_string = quote('Hello World!') # Encoding query parameters data = {'name': 'John Doe', 'age': 30} encoded_query = urlencode(data)
Example
This example shows how to encode a URL path segment and query parameters safely for use in a URL.
from urllib.parse import quote, urlencode # Encode a URL path segment path = 'Hello World!' encoded_path = quote(path) # Encode query parameters params = {'name': 'John Doe', 'city': 'New York'} encoded_params = urlencode(params) # Combine to form a full URL url = f'https://example.com/{encoded_path}?{encoded_params}' print(url)
Common Pitfalls
Not encoding special characters: Characters like spaces, &, ?, and / can break URLs if not encoded.
Using quote for query parameters: It's better to use urlencode for query strings because it handles key-value pairs and multiple values correctly.
Forgetting to decode URLs: When reading URLs, use urllib.parse.unquote to decode percent-encoded strings.
from urllib.parse import quote, urlencode # Wrong: encoding query parameters with quote params = 'name=John Doe&city=New York' wrong_encoded = quote(params) # Right: encoding query parameters with urlencode data = {'name': 'John Doe', 'city': 'New York'} right_encoded = urlencode(data) print('Wrong:', wrong_encoded) print('Right:', right_encoded)
Quick Reference
| Function | Purpose | Example Usage |
|---|---|---|
| quote(string, safe='') | Encode a URL path or part | quote('Hello World!') -> 'Hello%20World%21' |
| urlencode(dict_or_seq) | Encode query parameters | urlencode({'name':'John'}) -> 'name=John' |
| unquote(string) | Decode percent-encoded string | unquote('Hello%20World%21') -> 'Hello World!' |