Skip to content
shellhacks.dev
Python

URL encode a string

Percent-encode a string with urllib.parse.quote. A slash is kept by default, so pass safe='' for a query value, and use quote_plus for form data.

1 min read
Summarize in AI

A value goes into a URL, and spaces, ampersands and slashes in it would change the meaning of the address.

Python
from urllib.parse import quote, quote_plus, urlencode

s = "a b/c&d=é"
print(quote(s))
print(quote(s, safe=""))
print(quote_plus(s))
print(urlencode({"q": s, "page": 2}))
Text
a%20b/c%26d%3D%C3%A9
a%20b%2Fc%26d%3D%C3%A9
a+b%2Fc%26d%3D%C3%A9
q=a+b%2Fc%26d%3D%C3%A9&page=2

quote replaces unsafe bytes with percent escapes of their UTF-8 form, so the accented letter becomes two. By default the slash is left alone, because the function is meant for URL paths, and safe="" encodes it too, which a query value needs. quote_plus writes a space as a plus sign, the form encoding. All three are in urllib.parse, and urlencode builds a whole query string from a mapping.

Encode each part separately. Running quote over a complete URL also escapes its colon and question mark when you override safe, and encoding an already encoded string doubles every percent sign. For a path segment that must not contain a slash, pass safe="" as well.

Share

More snippets

Python

Read a CSV file

Read a CSV file with csv.reader and open it with newline=''. Without that argument a line break inside a quoted field is changed before the parser sees it.

2 min read
Python

Generate a UUID

Generate a random UUID with uuid.uuid4() and a repeatable one with uuid.uuid5(namespace, name). The hex attribute gives the form without hyphens.

2 min read
Python

Base64 encode a string

Encode with base64.b64encode(), which takes and returns bytes, so encode the string first and decode the result. The URL-safe variant swaps two characters.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.