Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
26 lines
829 B
Python
26 lines
829 B
Python
"""Case conversion helpers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
|
|
_SMALL_WORDS = {"a", "an", "and", "as", "at", "but", "by", "for", "in", "of", "on", "or", "the", "to"}
|
|
|
|
|
|
def title_case(text: str) -> str:
|
|
"""Capitalise each word except short function words (the first word is always capitalised)."""
|
|
out = []
|
|
for index, word in enumerate(text.split()):
|
|
if index > 0 and word.lower() in _SMALL_WORDS:
|
|
out.append(word.lower())
|
|
else:
|
|
out.append(word[:1].upper() + word[1:].lower())
|
|
return " ".join(out)
|
|
|
|
|
|
def snake_case(text: str) -> str:
|
|
"""Convert words, camelCase or kebab-case text to snake_case."""
|
|
text = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", text)
|
|
parts = re.split(r"[\s\-_]+", text.strip())
|
|
return "_".join(p.lower() for p in parts if p)
|