Drill

ProblemsPython › text

Title-case a heading

mediumtextPython

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.

title_case(heading: string) → string

Solve it in the editor →

Where you start

def title_case(heading: str) -> str:
    

Worked examples

CallResult
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)

The same problem in another language

More text problems in Python