The Style Guide

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Citadel

Problem

Given a string s and an optional list of lowercase exception words, title-case the string: capitalize the first letter of each whitespace-separated word, except that any word in the exceptions list stays lowercase unless it is the very first word of the string (which is always capitalized). When exceptions is None, fall back to a default set of common minor words (articles, conjunctions, and short prepositions such as a, an, the, and, or, but, in, on, of, for, to, at, by, is). Comparison against the exception set is case-insensitive, and the function returns the words rejoined with single spaces.

Not every word deserves the same treatment.

Example 1

Input:

s = "the lord of the rings", exceptions = null

Output:

"The Lord of the Rings"

Example 2

Input:

s = "a tale of two cities", exceptions = null

Output:

"A Tale of Two Cities"

Worked solution and explanation

Why this problem exists in real interviews

This tests string manipulation with conditional logic based on word position and membership in a stop-word set. Smart title case is a common formatting task that probes whether a candidate handles edge cases like the first word and short connector words.


Break down the requirements

Step 1: Resolve the exceptions set

When exceptions is None, fall back to a default set of minor words like a, an, the, and, or, but, in, on, of, for, to, at. These are lowercased unless they appear first. Build the default inside the function body, not as a mutable default argument.

Step 2: Split, transform, and rejoin

Split the string on whitespace. Capitalize the first word unconditionally. For subsequent words, capitalize only if the lowercased word is not in the exceptions set.


The solution

Position-aware capitalization with stop-word set
def title_case(s: str, exceptions: list = None) -> str:
    if exceptions is None:
        exceptions = ["a", "an", "the", "and", "or", "but", "in", "on", "of", "for", "to", "at", "by", "is"]
    minor = {word.lower() for word in exceptions}
    words = s.split()
    result_words = []
    for i in range(len(words)):
        word = words[i].lower()
        if i == 0 or word not in minor:
            result_words.append(word.capitalize())
        else:
            result_words.append(word)
    return " ".join(result_words)

Common follow-up questions