Categories
Python Answers

How to percent-encode URL parameters in Python?

Spread the love

Sometimes, we want to percent-encode URL parameters in Python.

In this article, we’ll look at how to percent-encode URL parameters in Python.

How to percent-encode URL parameters in Python?

To percent-encode URL parameters in Python, we can use the urllib.parse.quote method.

For instance, we write:

import urllib.parse

query = urllib.parse.quote("Müller".encode('utf8'))
print(query)
print(urllib.parse.unquote(query))

We call urllib.parse.quote to percent encode the "Müller" string.

We’ve to call encode to encode it as a utf-8 binary string before we do the percent encoding.

Then we call urllib.parse.unquote to percent decode the string back to the original string.

Therefore, we see:

M%C3%BCller
Müller

printed.

Conclusion

To percent-encode URL parameters in Python, we can use the urllib.parse.quote method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *