URL Encode in Python — Free Online Tool + Code Examples
Learn how to URL encode strings in Python using urllib.parse.quote(). Free online URL encoder plus ready-to-use Python 3 code examples.
How to URL Encode in Python
Python 3 provides URL encoding through the urllib.parse module. The two main functions are quote() for encoding path segments and quote_plus() for encoding form data (which converts spaces to + instead of %20). For building complete query strings, use urlencode().
urllib.parse.quote() Examples
from urllib.parse import quote, quote_plus, urlencode
# Basic URL encoding
text = 'hello world & goodbye'
print(quote(text)) # hello%20world%20%26%20goodbye
print(quote_plus(text)) # hello+world+%26+goodbye
# Encode with safe characters (preserve slashes)
path = '/api/v2/users/John Doe'
print(quote(path, safe='/')) # /api/v2/users/John%20Doe
# Encode Unicode characters
print(quote('café')) # caf%C3%A9
print(quote('日本語')) # %E6%97%A5%E6%9C%AC%E8%AA%9E
# Build complete query strings
params = {'q': 'hello world', 'lang': 'en', 'page': 1}
print(urlencode(params)) # q=hello+world&lang=en&page=1
quote() vs quote_plus()
| Input | quote() | quote_plus() |
|---|---|---|
hello world | hello%20world | hello+world |
a=1&b=2 | a%3D1%26b%3D2 | a%3D1%26b%3D2 |
/path/to | %2Fpath%2Fto | %2Fpath%2Fto |
Using the requests Library
import requests
# requests handles encoding automatically
response = requests.get('https://api.example.com/search', params={
'q': 'hello world & goodbye',
'lang': 'en'
})
print(response.url)
# https://api.example.com/search?q=hello+world+%26+goodbye&lang=en
When to Use Each
- quote() — Encode URL path segments. Spaces become
%20. Use thesafeparameter to preserve specific characters. - quote_plus() — Encode form data (application/x-www-form-urlencoded). Spaces become
+. - urlencode() — Build complete query strings from dictionaries. Uses
quote_plus()internally. - requests library — Handles encoding automatically when you pass
params.