How 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:

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

Watch a course Python - The Practical Guide

You can also use urllib.parse.quote to encode

import urllib.parse

string = 'value1'
encoded = urllib.parse.quote(string)
print(encoded)

This will output the encoded string : value1

You can also use requests.utils.requote_uri() for encode the string

import requests

string = 'value1'
encoded = requests.utils.requote_uri(string)
print(encoded)

This will output the encoded string : value1

Please note that requests library is not built-in python library and you have to install it first.