The Address Surgeon

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
Lob

Problem

parse_address gets address, one US mailing address from a raw customer feed stored as a single string like '123 Main St, Springfield, IL 62704', and returns a dict with its street, city, state and zip as separate fields. Each field holds just its value, with no stray whitespace around it.

One string hides a street, a city, a state, and a zip.

Example 1

Input:

address = "123 Main St, Springfield, IL 62704"

Output:

{"street":"123 Main St","city":"Springfield","state":"IL","zip":"62704"}

Example 2

Input:

address = "10 Elm St, Boston, MA 02108"

Output:

{"street":"10 Elm St","city":"Boston","state":"MA","zip":"02108"}

Worked solution and explanation

What this problem really is

This is a two-level parsing job wearing a formatting costume. Everyone splits on the comma, but the trap is the leading space the comma-and-space delimiter leaves on every field after the first, plus the state and zip riding together in the final segment. Skip the .strip() and the city comes back as ' Springfield' instead of 'Springfield'; coerce the zip with int() and '02108' silently becomes 2108.


Break down the requirements

Step 1: Split by comma to separate major sections

The record has three comma-separated parts: street, city, and a combined state-plus-zip. That first split gets you the major sections but leaves a leading space on every piece after the street.

Step 2: Split the last section again on the space

The third section still packs two values. Split it on whitespace so the two-letter state and the zip land in separate slots.

Step 3: Clean the fields and keep zip as text

Strip each field. The comma spacing is presentation, not data, so ' IL 62704' must lose its leading space before you touch it, and the zip stays a string so a leading zero survives.


The solution

Multi-level delimiter parsing with strip
def parse_address(address):
    parts = address.split(',')
    street = parts[0].strip()
    city = parts[1].strip()
    state_zip = parts[2].strip().split(' ')
    state = state_zip[0]
    zip_code = state_zip[1]
    result = {
        'street': street,
        'city': city,
        'state': state,
        'zip': zip_code
    }
    return result

Common follow-up questions