Python: 3 ways to convert a string to a URL slug

Updated: May 31, 2023 By: Khue Post a comment

This concise, practical article will show you 3 different ways to turn a string into a URL slug in Python.

Overview

In the context of web development, a URL slug is the last part of a URL that serves as a unique identifier of the page or resource in a human-readable format. It is typically a simplified version of the page’s title, containing only lowercase letters, numbers, and hyphens (some sites use underscores instead of hyphens).

For example, if we have a URL like this:

https://www.slingacademy.com/page/some-thing-special

Then the slug is:

some-thing-special

URL slugs are meant to make links more user-friendly and meaningful. When one person shares a URL on a social network, others can understand a bit of the content of the corresponding page through the slug.

Ways to turn a string into a URL slug

Using Python built-in string operations

This approach allows fine-grained control over the slug generation process and doesn’t rely on any third-party library.

The steps are:

  1. Convert the string to lowercase.
  2. Replace non-alphanumeric characters with spaces.
  3. Replace consecutive spaces with a single hyphen.
  4. Trim leading and trailing spaces.

Code implementation:

# Define a reusable function to convert a string to a slug
def string_to_slug(text):
    # Convert to lowercase
    text = text.lower()

    # Replace non-alphanumeric characters with spaces
    text = ''.join(char if char.isalnum() else ' ' for char in text)

    # Replace consecutive spaces with a single hyphen
    text = '-'.join(text.split())

    return text

# Example usage
title1 = "Hello buddy! How are you?"
slug1 = string_to_slug(title1)
print(slug1)

title2 = "Welcome to Sling Academy!"
slug2 = string_to_slug(title2)
print(slug2)

Output:

hello-buddy-how-are-you
welcome-to-sling-academy

Using regular expressions

Regular expressions can also help us get the job done quickly. In short, the process looks like this:

  1. Remove non-alphanumeric characters from the string using the pattern: r'\W+'.
  2. Replace spaces (except leading and trailing spaces, if any) with hyphens.
  3. Remove leading and trailing spaces.
  4. Convert the string to lowercase.

The technique has some similarities with the preceding one. Below is a code example:

import re

def string_to_slug(text):
    # Remove non-alphanumeric characters
    text = re.sub(r'\W+', ' ', text)

    # Replace spaces with hyphens
    # And prevent consecutive hyphens
    text = re.sub(r'\s+', '-', text)

    # Remove leading and trailing hyphens
    text = text.strip('-')

    # Convert to lowercase
    text = text.lower()

    return text

# Example usage
title1 = "Hello buddy! How  are you?   "
slug1 = string_to_slug(title1)
print(slug1)

title2 = "Are you a Python programmer or the Wolf of Wall Street?"
slug2 = string_to_slug(title2)
print(slug2)

Output:

hello-buddy-how-are-you
are-you-a-python-programmer-or-the-wolf-of-wall-street

Using the python-slugify library

python-slugify is an open-source library that can help us turn a string into a URL slug. It can not only reduce the amount of code that needs to be written but also is excellent at handling Unicode. To install the library, run the command below:

pip install python-slugify

Example:

from slugify import slugify

# Example usage
title1 = "Hello buddy! How are you? @#$%^&*()_+"
slug1 = slugify(title1)
print(slug1)

title2 = "Welcome to Sling Academy!"
slug2 = slugify(title2)
print(slug2)

Output:

hello-buddy-how-are-you
welcome-to-sling-academy

That’s it. The tutorial ends here. Enjoy the code, and have a nice day!