URL encoding is the process of converting special characters and symbols in a URL into a format that can be safely transmitted over the internet. Python provides a built-in module called urllib that makes it easy to perform URL encoding and decoding. In this tutorial, we will learn how to URL encode a string in Python using the urllib module.

To get started, make sure you have Python installed on your system. Open up a Python interpreter or create a new Python script file.

First, we need to import the urllib module:

import urllib

Once we have imported the urllib module, we can use its parse submodule to perform URL encoding. The urllib.parse module provides a function called quote() that takes a string as input and returns the URL-encoded version of that string.

Here’s an example:

original_string = ""Hello World!""
encoded_string = urllib.parse.quote(original_string)

Running this code will output:


As you can see, spaces have been replaced with %20 and the exclamation mark has been replaced with %21. This is the URL-encoded version of the original string.

You can also specify a custom encoding scheme using the optional safe parameter. For example, if you only want to encode spaces, you can do:

original_string = ""Hello World!""
encoded_string = urllib.parse.quote(original_string, safe=' ')

Running this code will output:


In this case, only spaces are encoded, and other special characters remain unchanged.

URL encoding is particularly useful when working with URLs that contain query parameters. Let’s look at an example:

base_url = ""https://www.example.com/search""
query_string = ""q=python tutorial""
encoded_query_string = urllib.parse.quote(query_string)
url = base_url + ""?"" + encoded_query_string

The output of this code will be:


In this example, the query string ““q=python tutorial”” is URL-encoded and appended to the base URL as a query parameter. The resulting URL is safe to use in HTTP requests.

And there you have it! You now know how to URL encode a string in Python using the urllib module. URL encoding is an essential skill when working with URLs and can help ensure that your applications handle special characters correctly. I hope you found this tutorial helpful!