0
0
PythonHow-ToBeginner · 3 min read

How to Encode URL in Python: Simple Guide with Examples

To encode a URL in Python, use 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.

python
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.

python
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)
Output
https://example.com/Hello%20World%21?name=John+Doe&city=New+York
⚠️

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.

python
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)
Output
Wrong: name%3DJohn%20Doe%26city%3DNew%20York Right: name=John+Doe&city=New+York
📊

Quick Reference

FunctionPurposeExample Usage
quote(string, safe='')Encode a URL path or partquote('Hello World!') -> 'Hello%20World%21'
urlencode(dict_or_seq)Encode query parametersurlencode({'name':'John'}) -> 'name=John'
unquote(string)Decode percent-encoded stringunquote('Hello%20World%21') -> 'Hello World!'

Key Takeaways

Use urllib.parse.quote to encode URL path segments safely.
Use urllib.parse.urlencode to encode query parameters as key-value pairs.
Never manually encode URLs; always use these functions to avoid errors.
Remember to decode URLs with urllib.parse.unquote when needed.
Spaces become %20 in paths and + in query strings when encoded.