Introduction
In web development, it is common to have URLs that contain readable words instead of random characters. These readable words are called slugs. Slugs are used to make URLs more user-friendly and easier to remember. In this challenge, you will create a function that converts a string to a URL-friendly slug.
String to Slug
Write a function slugify(s) that takes a string s as an argument and returns a slug. The function should perform the following operations:
- Convert the string to lowercase and remove any leading or trailing whitespace.
- Replace all special characters (i.e., any character that is not a letter, digit, whitespace, hyphen, or underscore) with an empty string.
- Replace all whitespace, hyphens, and underscores with a single hyphen.
- Remove any leading or trailing hyphens.
import re
def slugify(s):
s = s.lower().strip()
s = re.sub(r'[^\w\s-]', '', s)
s = re.sub(r'[\s_-]+', '-', s)
s = re.sub(r'^-+|-+$', '', s)
return s
slugify('Hello World!') ## 'hello-world'
Summary
In this challenge, you learned how to create a function that converts a string to a URL-friendly slug. You used string methods and regular expressions to remove special characters and replace whitespace, hyphens, and underscores with a single hyphen. By completing this challenge, you have gained a better understanding of how to manipulate strings in Python.