Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

URL Encode A String In Python

This code encodes (aka quotes) a string for use in a url query string path:

Code

import urllib.parse

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

print(url_string)

Results

The%20quick%20brown%20fox

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

Code

import urllib.parse

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

print(url_string)

Results

The+quick+brown+fox

More details in the docs: