Avoid treating plus signs as spaces in a URL path
Also published in our primary archive.
A plus sign has different conventions in different URL components. Form-style query-string decoding commonly interprets + as a space, but a URL path may contain a literal plus sign. This example splits /team+alpha/notes%20draft into URL components and applies urllib.parse.unquote() to the path. The percent escape %20 becomes a space, while team+alpha remains unchanged.
The urllib.parse documentation distinguishes URL parsing and quoting utilities. The important choice is unquote(), which decodes percent-encoded sequences, rather than unquote_plus(), whose documented purpose also replaces plus signs with spaces. Split first, then apply component-appropriate decoding: query parameters may use form conventions, but that convention should not be transferred to a path merely because both are strings in the same URL.
The assertions show the component boundary and decoded value for this controlled input. They do not validate that the path names a real resource, prevent traversal, or establish a universal server-side interpretation. Some applications define their own routing or normalization rules, so request handling should apply the project’s URL policy after parsing. The APIs shown are long-standing standard-library functions and have no newer Python-version minimum. AI assistance was used to draft this article.
from urllib.parse import unquote, urlsplit
url = "https://example.test/team+alpha/notes%20draft?label=a+b"
parts = urlsplit(url)
decoded_path = unquote(parts.path)
assert parts.path == "/team+alpha/notes%20draft"
assert parts.query == "label=a+b"
assert decoded_path == "/team+alpha/notes draft"
print(decoded_path)
/team+alpha/notes draft