Normalize Name
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
Problem
Names coming off a signup form carry stray whitespace and whatever casing the user typed. Return each name as a clean display name, every word capitalized with the rest of it lowercased.
Names are messy. Standardize them.
Example 1
Input:
name = "ada lovelace"
Output:
"Ada Lovelace"
Example 2
Input:
name = " grace HOPPER "
Output:
"Grace Hopper"
Worked solution and explanation
What this really tests
This is whitespace normalization dressed up as a casing problem. Everyone sees the capitalization; the part that separates candidates is the spacing. Reach for name.title() and the casing comes out right, but every run of spaces and every leading or trailing blank survives untouched, so ' grace HOPPER ' comes back as ' Grace Hopper ' and the cleanup the form data needed never happens.
Break down the requirements
Step 1: Split the name into words
Call name.split() with no argument. That form splits on any whitespace run (spaces, tabs, newlines) and drops empty pieces, so the stray padding disappears before you touch a single letter.
Step 2: Capitalize the first letter of each word and lowercase the rest
Uppercase the first character and lowercase everything after it. The second half is the one people skip: without it 'HOPPER' keeps shouting and 'heLLO' stays mangled. Because the split never yields an empty word, word[0] is always safe.
Step 3: Rejoin with spaces
Join the cleaned words with exactly one space. Because the split already threw the original spacing away, the output spacing is now yours to decide, not inherited from the input.
The solution
def normalize_name(name):
words = name.split()
result_words = []
for word in words:
titled = word[0].upper() + word[1:].lower()
result_words.append(titled)
result = ' '.join(result_words)
return resultCommon follow-up questions
- What if names contain hyphens like 'smith-jones'? (Tests treating hyphens as an extra word boundary only inside each whitespace word.)
- What about particles like 'de', 'von', 'van' that stay lowercase? (Tests a lookup set of exceptions that should not be capitalized.)
- What changes when names arrive with accents or in non-Latin scripts, like 'élodie'? (Tests knowing that `upper()` and `lower()` are Unicode-aware, and where one-to-one casing breaks, such as 'ß'.)