Encode local query parameters with urlencode
Also published in our primary archive.
Build a query string from local data with urlencode() instead of manually joining text around & and =. Manual construction can misrepresent spaces, slashes, Unicode text, or an ampersand included in a value. Here, a list of two-element tuples deliberately supplies two tag values and fixes their output order.
urlencode() returns ASCII query text. With its default quote_plus strategy, the city name İzmir is UTF-8 percent-encoded, the slash in a/b becomes %2F, and the space in two words becomes +. The assertion checks that exact encoded string before it is printed. It therefore checks the known fixture values and Python’s documented default quoting behavior; it does not establish what a remote service expects.
A sequence of pairs is especially useful when duplicates or ordering matter. A mapping is also accepted, while sequence values in a mapping can be expanded with doseq=True. The resulting query still needs to be placed into a URL component appropriately; this example only creates local text and performs no network activity. urlencode() works in Python 3.2+ for this string-based example. The optional quote_via argument is available from Python 3.5 when %20-style space encoding or different quoting behavior is required. See the official urllib.parse documentation.
AI assistance disclosure: this article was drafted with AI assistance and should be checked against the receiving service’s parameter format.
from urllib.parse import urlencode
parameters = [
("city", "İzmir"),
("tag", "a/b"),
("tag", "two words"),
]
query = urlencode(parameters)
assert query == "city=%C4%B0zmir&tag=a%2Fb&tag=two+words"
print(query)
city=%C4%B0zmir&tag=a%2Fb&tag=two+words