Introduction
In Python, a kebab case string is a string where each word is separated by a hyphen. For example, "hello-world" is a kebab case string. In this challenge, you will be tasked with writing a function that converts a given string to kebab case.
Kebabcase string
Write a Python function called to_kebab_case(s) that takes a string s as its input and returns the kebab case version of the string. The function should perform the following steps:
- Replace any
-or_with a space, using the regexpr"(_|-)+". - Match all words in the string,
str.lower()to lowercase them. - Combine all words using
-as the separator.
from re import sub
def kebab(s):
return '-'.join(
sub(r"(\s|_|-)+"," ",
sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
lambda mo: ' ' + mo.group(0).lower(), s)).split())
kebab('camelCase') ## 'camel-case'
kebab('some text') ## 'some-text'
kebab('some-mixed_string With spaces_underscores-and-hyphens')
## 'some-mixed-string-with-spaces-underscores-and-hyphens'
kebab('AllThe-small Things') ## 'all-the-small-things'
Summary
In this challenge, you learned how to convert a string to kebab case in Python. You used re.sub() to replace any - or _ with a space, re.sub() to match all words in the string, str.lower() to lowercase them, and str.join() to combine all words using - as the separator.