easy +8 pts

Kebab Case Converter

Convert strings to kebab-case by lowercasing and joining words with hyphens.

Write a Python function `to_kebab_case(s: str) -> str` that takes an input string `s` and returns its kebab-case version. Kebab-case rules: 1. Split the input into words. 2. Words are separated by spaces, underscores, or hyphens. Additionally, camelCase boundaries (a lowercase letter followed by an uppercase letter) count as word boundaries. 3. Any non-alphanumeric characters (like punctuation) are treated as separators and are not part of any word. 4. Convert all letters to lowercase. 5. Join the resulting words with hyphens. Examples: - `"Hello World"` -> `"hello-world"` - `"foo_bar"` -> `"foo-bar"` - `"already-kebab"` -> `"already-kebab"` - `"camelCaseExample"` -> `"camel-case-example"` - `"Hello, World!"` -> `"hello-world"` - `"Multiple spaces"` -> `"multiple-spaces"` - `"__double__underscores__"` -> `"double-underscores"` - `"already-kebab"` -> `"already-kebab"`

Constraints

Input string length is between 0 and 200. Input may contain any printable ASCII characters. Return a string. For empty input or input with no words, return an empty string. The implementation should be O(n) time where n is the length of the string.

Example

>>> to_kebab_case('Hello World')
'hello-world'
>>> to_kebab_case('foo_bar')
'foo-bar'
>>> to_kebab_case('camelCaseExample')
'camel-case-example'
>>> to_kebab_case('Hello, World!')
'hello-world'
8 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think of constructing words by iterating through characters and identifying boundaries.
Use a set of allowed alphanumeric characters and a flag to track if you are inside a word.
Handle camelCase by detecting when a lowercase letter is followed by an uppercase letter.
Trim extra hyphens by only adding a hyphen when you start a new word after already having at least one word.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.