W3docs

How to urlencode a querystring in Python?

You can use the urllib.parse.urlencode() function to urlencode a querystring in Python.

You can use the urllib.parse.urlencode() function to urlencode a querystring in Python. Here is an example of how to use the function to urlencode a querystring with multiple parameters:

urlencode a querystring in Python

import urllib.parse

query_params = {'param1': 'value1', 'param2': 'value2', 'param3': 'value3'}
querystring = urllib.parse.urlencode(query_params)
print(querystring)

This will output the querystring in the following format: param1=value1&param2=value2&param3=value3

You can also use urllib.parse.quote to encode individual values.

use urllib.parse.quote to encode

import urllib.parse

string = 'hello world & test'
encoded = urllib.parse.quote(string)
print(encoded)

This will output the encoded string: hello%20world%20%26%20test

You can also use urllib.parse.quote_plus to encode query parameters.

use urllib.parse.quote_plus to encode

import urllib.parse

string = 'hello world & test'
encoded = urllib.parse.quote_plus(string)
print(encoded)

This will output the encoded string: hello+world+%26+test

quote_plus is typically preferred for query strings because it converts spaces to + instead of %20, matching traditional form-encoding behavior.