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.
A value goes into a URL, and spaces, ampersands and slashes in it would change the meaning of the address.
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}))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=2quote 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.