0
0
PythonHow-ToBeginner · 3 min read

How to URL Encode in Python: Simple Guide with Examples

In Python, you can URL encode strings using urllib.parse.quote for individual strings or urllib.parse.urlencode for query parameters. These functions convert special characters into a format safe for URLs.
📐

Syntax

Use urllib.parse.quote(string, safe='') to encode a single string, where string is the text to encode and safe specifies characters to leave unencoded.

Use urllib.parse.urlencode(query, doseq=False) to encode a dictionary or sequence of two-element tuples into URL query parameters.

python
from urllib.parse import quote, urlencode

# Encoding a single string
encoded_string = quote('hello world!')

# Encoding query parameters
params = {'name': 'John Doe', 'age': 30}
encoded_params = urlencode(params)
💻

Example

This example shows how to encode a string with spaces and special characters, and how to encode a dictionary of query parameters for a URL.

python
from urllib.parse import quote, urlencode

# Encode a single string
text = 'hello world!'
encoded_text = quote(text)
print('Encoded string:', encoded_text)

# Encode query parameters
params = {'name': 'John Doe', 'city': 'New York', 'age': 25}
encoded_query = urlencode(params)
print('Encoded query:', encoded_query)
Output
Encoded string: hello%20world%21 Encoded query: name=John+Doe&city=New+York&age=25
⚠️

Common Pitfalls

One common mistake is using quote when you want to encode multiple query parameters; use urlencode instead. Also, forgetting to import urllib.parse causes errors.

Another pitfall is not handling spaces correctly: quote encodes spaces as %20, while urlencode uses + for spaces in query strings.

python
from urllib.parse import quote, urlencode

# Wrong: encoding multiple parameters with quote
params = {'name': 'Alice', 'city': 'Los Angeles'}
wrong_encoded = quote(str(params))
print('Wrong encoding:', wrong_encoded)

# Right: use urlencode for parameters
right_encoded = urlencode(params)
print('Right encoding:', right_encoded)
Output
Wrong encoding: %7B%27name%27%3A%20%27Alice%27%2C%20%27city%27%3A%20%27Los%20Angeles%27%7D Right encoding: name=Alice&city=Los+Angeles
📊

Quick Reference

  • quote(string, safe=''): Encode a single string, escaping all characters except those in safe.
  • urlencode(query, doseq=False): Encode a dictionary or list of tuples into URL query parameters.
  • Use quote for path segments and urlencode for query strings.

Key Takeaways

Use urllib.parse.quote to encode individual strings safely for URLs.
Use urllib.parse.urlencode to encode dictionaries or sequences into query strings.
quote encodes spaces as %20, urlencode encodes spaces as + in query parameters.
Always import urllib.parse before using these functions.
Avoid using quote to encode multiple parameters; use urlencode instead.