Title-case a heading
The CMS title-cases headings on save, but the house style leaves the small joining words in lowercase unless one of them opens the heading.
- Capitalise the first letter of every word and lowercase the rest of it.
- These stay lowercase: a, an, and, as, at, but, by, for, in, of, on, or, the, to.
- Except the very first word, which is always capitalised.
- Words are separated by single spaces.
title_case(heading: string) → string
Where you start
def title_case(heading: str) -> str:
Worked examples
| Call | Result |
|---|---|
title_case("the lord of the rings") | "The Lord of the Rings" |
title_case("a tale OF two cities") | "A Tale of Two Cities" |
title_case("hello") | "Hello" |
title_case("of mice and men") | "Of Mice and Men" |
Hint
Handle index 0 as its own case, then let the small-word list decide for the rest.
Reference solution in Python
def title_case(heading: str) -> str:
small = {'a', 'an', 'and', 'as', 'at', 'but', 'by', 'for', 'in', 'of', 'on', 'or', 'the', 'to'}
if heading == '':
return ''
parts = []
for i, w in enumerate(heading.split(' ')):
low = w.lower()
parts.append(low if i > 0 and low in small else low.capitalize())
return ' '.join(parts)