This is all for Python 3.

Encode

Quote

  • urllib.parse.quote
  • urllib.parse.quote_plus

    Like quote(), but also replace spaces with plus signs, as required for quoting HTML form values when building up a query string to go into a URL.

    Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to β€˜/’.

  • urllib.parse.urlencode
    • Pass key-value pairs to encode for query params in a URL. Uses quote_plus internally.
  • urllib.parse.parse_qs
import urllib.parse
urllib.parse.quote('Hello, world!')
# 'Hello%2C%20world%21'

urllib.parse.quote_plus('Hello, world!')
# 'Hello%2C+world%21'

URL params:

params = {'q': 'Python URL encoding', 'abc': '134'}
urllib.parse.urlencode(params)
# 'q=Python+URL+encoding&abc=134'
params_str = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
url = f"http://www.musi-cal.com/cgi-bin/query?{params_str}"

Decode

urllib.parse.unquote('Hello%2C%20world%21')
# 'Hello, world!'
urllib.parse.unquote_plus('Hello%2C+world%21')
# 'Hello, world!'
urllib.parse.parse_qs('q=Python+URL+encoding&abc=134')
# {'q': ['Python URL encoding'], 'abc': ['134']}

urllib.parse.parse_qsl('q=Python+URL+encoding&abc=134')
# [('q', 'Python URL encoding'), ('abc', '134')]

Note urlparse won’t separate query params.

urllib.parse.urlparse('q=Python+URL+encoding&abc=134')
# ParseResult(scheme='', netloc='', path='q=Python+URL+encoding&abc=134', params='', query='', fragment='')

urllib.parse.urlparse('https://example.com?q=Python+URL+encoding&abc=134')
# ParseResult(scheme='https', netloc='example.com', path='', params='', query='q=Python+URL+encoding&abc=134', fragment='')

Alias

This can be set as a Bash alias.

$ alias urlencode='python3 -c \
"import sys, urllib.parse
print(urllib.parse.quote_plus(sys.argv[1]))"
'

$ urlencode 'Hello, world!'
Hello%2C+world%21