URL Encode A String In Python

September - 2021

Code to encode/quote a string for use in a url query string path:

#!/usr/bin/env python3

import urllib.parse

string = "The quick brown fox"
url_string = urllib.parse.quote(string)

print(url_string)

Returns:

The%20quick%20brown%20fox

There is also this one which uses + for spaces instead of %20:

#!/usr/bin/env python3

import urllib.parse

string = "The quick brown fox"
url_string = urllib.parse.quote_plus(string)

print(url_string)

Returns:

The+quick+brown+fox

More details in the docs: