Developer Documentation
Python
Updated September 19, 2026

URL Encoding and Decoding in Python

Percent-encode URL components correctly and distinguish path, query, and form encoding in Python.

URL encoding is context-sensitive. A path segment, a query value, and application/x-www-form-urlencoded data do not use exactly the same escaping rules, so prefer APIs designed for the specific component you are building.

Quick Start#

The following example uses the standard Python API or a widely used package for this task.

Encode a component#

Python
1from urllib.parse import quote, unquote23value = "café & tea + cake"4encoded = quote(value, safe="")5decoded = unquote(encoded)67print(encoded)8print(decoded)

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Build a query string#

Python
1from urllib.parse import urlencode23query = urlencode({"q": "café & tea", "page": })4url = f"https://example.com/search?{query}"5print(url)

Important Notes#

quote/unquote implement percent encoding, while urlencode follows form-style query conventions such as encoding spaces as +.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement URL Encoding in other languages: