Last modified: October 02, 2021

Python: How to Convert String To URL

Today we'll learn about two ways to convert a string to a URL.

Using the slugify library

slugify: Convert a string to a valid URL (slug).

So, first, we need to install it via pip.

pip install python-slugify 

How to use slugify:


slugify(string)


In the following example, we'll see how to convert a string to a URL.


from slugify import slugify

# String
string = "How to learn Python"

# Convert String To URL
url = slugify(string)

# Print
print(url)

Output:

how-to-learn-python

If you want to replace the spaces with something else, set the separator parameter.


# Convert String To URL with '%'
url = slugify(string, separator='%')

# Print
print(url)

Output:

how%to%learn%python

As you can see, the spaces have been replaced with %.


Let's see the output of a string that contains symbols.


# String
string = ".How+ to/learn/$$Python"

# Convert String To URL
url = slugify(string)

# Print
print(url)

Output:

how-to-learn-python

Using the urllib.parse module

As you know, the modules come with PYTHON so, you don't need to install it.

How to use urllib.parse:


urllib.parse.quote_plus(string)


Let's see an example.


import urllib.parse

# String
query = 'Hellö Py/tutorial'

# Convert String To URL
url = urllib.parse.quote_plus(query)

# Print
print(url)

Output:

Hell%C3%B6+Py%2Ftutorial