PREP WITH PROOF
Menu
PYTHON & APIS / PRACTICAL GUIDE

URL Percent-Encoding in Python: Paths, Query Strings and Plus Signs

Build Python URLs without losing plus signs, slashes, repeated parameters or Unicode. Compare quote and urlencode, avoid double decoding, and run a tested lab.

THE QUICK ANSWER

Encode raw data for the URL component that will contain it. In Python, quote(value, safe="") encodes a single path segment, while urlencode builds a form-style query string from keys and values. A plus sign means space in form decoding, but is not universally a space in URLs. Split structure before decoding, preserve repeated query parameters when required, and decode exactly once at the boundary that owns that representation.

Start with the data contract, not a global replace

A search term such as C++ & tea contains characters that become meaningful in a query string. A document identifier such as Q4/a+b?# contains characters that can become path, query or fragment delimiters. Concatenating those values directly into a URL confuses application data with URL structure. These are invented inputs for a reproducible example, not production incident data.

Before choosing an encoder, label each input: raw identifier, raw query value, already encoded component, or complete URL. Then identify which layer owns serialization. If an HTTP client accepts a parameters mapping or list, pass raw values to that API according to its documentation. Encoding values first can cause the client to encode the percent signs again.

The useful invariant is not that a URL contains no punctuation. It is that parsing the assembled URL recovers the intended structure and decoding each owned component recovers the intended data. Our lab checks those properties locally rather than assuming that a visually plausible link is correct.

Choose an encoder by component

Percent escapes represent bytes. With UTF-8 text, a non-ASCII character can become several percent-encoded bytes. The structure around those bytes still matters: encoding an entire absolute URL as if it were one value also encodes its scheme and separators. Assemble fixed structure and separately encoded data instead.

The table describes the Python operations used in this guide. It is not a claim that every API uses form-style query semantics. A service can define a different query grammar or canonicalization scheme; follow that contract when present.

Input and destinationOperationImportant boundary
One raw path segmentquote(value, safe="")Escapes a slash inside the value; does not validate route semantics
Raw query name/value pairsurlencode(pairs)Encodes names and values; joins them with & and =
A raw list-valued query parameterurlencode(mapping, doseq=True)Produces repeated keys rather than a list representation
Encoded path componentunquote(component, errors="strict")Does not turn + into space; malformed percent syntax needs separate handling
Form-style encoded queryparse_qsl(query, keep_blank_values=True)Returns pairs, preserving repeated names and empty values
Complete URLurlsplit then inspect componentsParsing alone is not URL validation or an authorization check

Source: Python 3.12: urllib.parse quoting, query parsing and security notes ↗

Why C++ becomes C%2B%2B and a space can become +

In form-style query serialization, a literal plus must be escaped so it will not be confused with the representation of a space. Our fixture produces q=C%2B%2B+%26+tea. Parsing that query recovers the original C++ & tea. Simply replacing every space with + would leave the original plus signs ambiguous.

Form parsing treats + as a space before percent-decoding the value. This convention belongs to application/x-www-form-urlencoded, including the form-style query operations used here. Applying that decoder to an arbitrary path component can corrupt a literal plus.

The lab makes the difference explicit: unquote("a+b") keeps a+b, whereas unquote_plus("a+b") returns a b. If the API requires percent-encoded spaces, urlencode with quote_via=quote and safe="" produces that representation. Choose the documented representation before signing or comparing request strings; do not rewrite it afterward.

Source: WHATWG URL Standard: application/x-www-form-urlencoded parsing ↗

A slash inside an identifier is a separate routing decision

The path example uses a fixed /items/ prefix followed by one encoded identifier. For Q4/a+b?#, the result is /items/Q4%2Fa%2Bb%3F%23. Python urlsplit sees that whole encoded value in the path and an empty fragment. After selecting that component, our decoder recovers the identifier exactly.

Python quote preserves / by default. That default is useful when deliberately quoting a path containing separators, but unsuitable when a slash belongs to one opaque value. safe="" is the intentional choice for the one-segment example. Calling quote on a whole URL with that setting creates a quoted value, not a usable replacement for the original absolute URL.

An encoded slash is not a promise that your router will preserve one segment end to end. A server, framework or proxy may reject it or process it differently. Decide whether such identifiers are supported, test the actual route, or design an API that puts the identifier in a suitable query value or request body. The local fixture performs no HTTP requests.

Quoting is also not a path policy: quote("..", safe="") remains "..". If identifiers must exclude empty strings or complete dot segments, reject them explicitly before assembling a route. Do not rely on escaping punctuation to establish which objects a caller may access.

Keep the query data model intact

Our query is an ordered list of pairs with two tag entries and one empty value. parse_qsl with keep_blank_values=True recovers the original list. Converting that list straight to a dictionary keeps only the last tag value in this fixture. That is a data-model change, even though the resulting mapping looks convenient.

The default parsing call drops the empty value in the example. Choose whether missing and empty mean the same thing for your endpoint. For a filter form, empty may mean clear this filter; missing may mean retain the previous setting. Encoding cannot make that business decision for you.

For a mapping whose values are lists, doseq=True expands each list element into its own parameter. Alternatively, pass explicit pairs when ordering or repeated keys matter. Our lab uses strings throughout, making the intended serialization clear without relying on implicit conversion of booleans, null-like values or numeric application objects.

Source: Python 3.12: urllib.parse quoting, query parsing and security notes ↗

Decode once, after identifying the component

The literal raw text %2F is not the same representation as an encoded slash. When that literal text is encoded as data, it becomes %252F. One decoding step returns %2F; a second returns /. The second result is a different value. Repeated decoding until a string stops changing silently erases this distinction.

Our complete-URL fixture also demonstrates the wrong operation order. Decoding the entire URL before splitting it turns encoded punctuation into structural delimiters, including a fragment marker. Splitting the encoded URL first allows the code to select the path suffix and query separately, then use the appropriate decoder for each.

Double encoding is not always a bug. If a raw field intentionally contains a percent escape as literal text, escaping its percent sign is correct. The diagnostic question is who supplied raw data and who supplied serialized data. Give those representations distinct names in code, and avoid passing an encoded string into an API expecting raw parameters.

Source: RFC 3986: percent encoding and component boundaries ↗

Run the complete offline lab

Save this program as url_encoding_lab.py and run python url_encoding_lab.py without optimization flags, so assertions remain enabled. We ran the exact listing on Python 3.12.14: all 1,633 checks passed. It uses only the standard library and makes no network calls. The example.test URL is an invented test destination.

Two hundred seeded strings include reserved punctuation, spaces, plus signs, percent signs, accented text, a combining mark, a Chinese character and a non-BMP emoji. A separate byte-by-byte encoder supplies expected percent escapes. The checks also round-trip query pairs and complete URL components, alongside explicit malformed-input and duplicate-value examples.

The helper rejects malformed percent triplets and requests strict UTF-8 decoding. It expects a separated encoded component, not a complete URL or a form query. It does not enforce a route allowlist, reject control characters as application data, validate hosts, or reproduce a browser parser. Treat it as an encoding boundary demonstration rather than a general URL safety library.

import random
import re
from urllib.parse import (quote, quote_plus, unquote, unquote_plus,
                          urlencode, parse_qsl, urlsplit, urlunsplit)

checks = 0

def check(condition):
    global checks
    assert condition
    checks += 1

def rejects(error, action):
    try:
        action()
    except error:
        check(True)
    else:
        raise AssertionError('expected rejection')

UNRESERVED = b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'

def byte_oracle(text, form=False):
    # Deliberately separate byte-by-byte encoder for comparison.
    return ''.join(chr(b) if b in UNRESERVED else
                   '+' if form and b == 32 else f'%{b:02X}'
                   for b in text.encode('utf-8'))

def decode_component(text):
    # This helper expects already-separated encoded component text.
    if re.search(r'%(?![0-9A-Fa-f]{2})', text):
        raise ValueError('malformed percent escape')
    return unquote(text, encoding='utf-8', errors='strict')

check(quote('a/b c', safe='') == 'a%2Fb%20c')
check(quote('a/b c') == 'a/b%20c')
check(quote_plus('C++ notes') == 'C%2B%2B+notes')
check(unquote('a+b') == 'a+b')
check(unquote_plus('a+b') == 'a b')
check(quote('caf\u00e9', safe='') == 'caf%C3%A9')
check(quote('e\u0301', safe='') == 'e%CC%81')
check(quote('\u00e9', safe='') != quote('e\u0301', safe=''))
check(quote('%2F', safe='') == '%252F')
check(decode_component('%252F') == '%2F')
check(decode_component(decode_component('%252F')) == '/')
check(unquote('%ZZ') == '%ZZ')
check(unquote('%FF') == '\ufffd')
for bad in ('%', '%2', '%ZZ', 'ok%20bad%q0'):
    rejects(ValueError, lambda bad=bad: decode_component(bad))
rejects(UnicodeDecodeError, lambda: decode_component('%FF'))
rejects(UnicodeEncodeError, lambda: quote('\ud800', safe=''))

pairs = [('q', 'C++ & tea'), ('tag', 'red'), ('tag', 'blue'), ('empty', '')]
query = urlencode(pairs)
check(query == 'q=C%2B%2B+%26+tea&tag=red&tag=blue&empty=')
check(parse_qsl(query, keep_blank_values=True) == pairs)
check(parse_qsl(query) == pairs[:-1])
check(parse_qsl(urlencode(pairs, quote_via=quote, safe=''),
                keep_blank_values=True) == pairs)
check(urlencode({'tag': ['red', 'blue']}, doseq=True) == 'tag=red&tag=blue')
check(dict(parse_qsl(query, keep_blank_values=True))['tag'] == 'blue')

item = 'Q4/a+b?#'
path = '/items/' + quote(item, safe='')
url = urlunsplit(('https', 'example.test', path, query, ''))
parts = urlsplit(url)
check(parts.netloc == 'example.test')
check(parts.path == '/items/Q4%2Fa%2Bb%3F%23')
check(parts.fragment == '')
check(decode_component(parts.path[len('/items/'):]) == item)
check(parse_qsl(parts.query, keep_blank_values=True) == pairs)
# The wrong order turns data into URL structure.
check(urlsplit(unquote(url)).fragment != '')
check(quote(url, safe='').startswith('https%3A%2F%2F'))
# Quoting does not reject special complete path segments.
check(quote('..', safe='') == '..')

rng = random.Random(87)
alphabet = 'aZ09 -._~+/%&=?#*\u00e9\u0301\u6c34\U0001f600'
for _ in range(200):
    value = ''.join(rng.choice(alphabet) for _ in range(rng.randrange(21)))
    encoded = quote(value, safe='')
    form = quote_plus(value, safe='')
    check(encoded == byte_oracle(value))
    check(form == byte_oracle(value, form=True))
    check(decode_component(encoded) == value)
    check(unquote_plus(form, encoding='utf-8', errors='strict') == value)
    sample = [('q', value), ('q', '+'), ('blank', '')]
    check(parse_qsl(urlencode(sample), keep_blank_values=True) == sample)
    assembled = urlunsplit(('https', 'example.test', '/items/' + encoded,
                           urlencode(sample), ''))
    split = urlsplit(assembled)
    check(split.netloc == 'example.test' and split.fragment == '')
    check(decode_component(split.path[len('/items/'):]) == value)
    check(parse_qsl(split.query, keep_blank_values=True) == sample)
print(f'PASS: {checks} checks; offline Python string/byte behavior only')
print(url)

Malformed escapes and malformed UTF-8 are different failures

The explicit checks distinguish %ZZ, which has invalid escape syntax, from %FF, which represents a byte that is not a valid standalone UTF-8 sequence. In our tested Python version, the default unquote leaves %ZZ unchanged and substitutes a replacement character for %FF. Successful return from a decoder therefore does not prove that the input matched your expected encoding.

If malformed data should be rejected, specify that policy and test it. Our helper combines a percent-triplet syntax check with errors="strict" for UTF-8. Applying only the UTF-8 option would not reject the malformed escape syntax case. Conversely, valid escape syntax does not guarantee valid decoded text.

The composed character é and the decomposed sequence e plus a combining accent have different bytes and different escapes in the lab. Both round-trip. Percent encoding does not normalize Unicode. If an identifier system requires a normalization policy, define it before serialization and apply it consistently to stored identities as well as incoming lookups.

Debug the representation at each boundary

For a lost plus sign, compare the raw value, serialized query and parsed value. For an unexpected extra parameter, inspect whether an ampersand was inserted as data without escaping. For a missing suffix, inspect whether a hash sign became a fragment delimiter. The named fixture values make these cases visible without logging real credentials or private query values.

For signed requests or cache keys, preserve the endpoint’s exact canonicalization rules, including ordering and the treatment of repeated or empty parameters. Our round-trip checks prove recovery of values under the selected Python functions; they do not prove that two different serializations receive identical treatment by a remote service.

Once the local encoding contract passes, test the actual HTTP client, proxy and application route with representative non-sensitive fixtures. Keep raw values separate from serialized components, select one owner for each encoding step, and compare structure before comparing appearance. That makes URL bugs reproducible instead of turning them into a sequence of ad hoc replacements.

KEEP THESE THREE THINGS

Your next steps

  1. Choose encoding rules for the destination component, not the whole URL.
  2. Use raw values with the serializer that owns query construction.
  3. Preserve duplicate names and empty values when the API requires them.
  4. Split encoded structure before decoding individual components once.
  5. Test server routing separately; quoting is not validation or authorization.

Sources & official resources

Linked resources checked on 2026-11-03. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →