Editor

Clean a City Name

Beginner · Write the code · from Extracting Information from Data: Cleaning, Filtering and Metadata

From the lesson: Why does data need cleaning?

The council runs a survey: Which snack should the stand add? The answer box is an open text field, and that causes trouble. Depending on how data were collected, they may not be uniform: when people type freely, each person chooses their own spelling, capitalization and abbreviations.

Read this part of the lesson

A sign-up form has an open text box for the city a student lives in. Write clean_city(entry) that makes the entries uniform:

1. Remove spaces at the start and end, and turn any run of spaces inside the name into one space.

2. If the entry (ignoring capitalization) is one of these abbreviations, return the full name: nyc is New York, la is Los Angeles, sf is San Francisco.

3. Otherwise return the name with each word capitalized.

clean_city('  new york ')  ->  'New York'
clean_city('NYC')          ->  'New York'
ABBREVIATIONS = {"nyc": "New York", "la": "Los Angeles", "sf": "San Francisco"}
def clean_city(entry):
# Tidy the spaces, check the abbreviations, then fix the capitals
pass

What Check runs

Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.

RunsExpected output
print(clean_city(" new york "))New York
print(clean_city("NYC"))New York
print(clean_city("los angeles"))Los Angeles

More Data Filtering exercises

All Python exercises · 50 practice problems