Where the Lines Break
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
Access-log lines arrive with ragged whitespace: fields run together under uneven spacing and stray leading or trailing gaps. Break each line into its whitespace-separated fields, keeping only the real tokens, and hand back an empty list when a line holds nothing but whitespace.
Every record hides its fields behind noise. Pull the real ones loose.
Example 1
Input:
line = "GET /home 200"
Output:
["GET","/home","200"]
Example 2
Input:
line = " POST /login 503 "
Output:
["POST","/login","503"]
Worked solution and explanation
What this really is
Underneath the log-parsing costume, this is a one-liner whose entire difficulty is one fork: .split() versus .split(' '). The bare call collapses every run of whitespace and silently drops the empty gaps, so padded and ragged lines come out clean. Pass a literal space and Python preserves every empty string sitting between your double spaces. Reach for .split(' ') on a line like ' POST /login ' and you hand back a list studded with '' tokens that no downstream parser asked for. It also will not split a tab- or newline-delimited line at all.
How to get there
Step 1: Split on whitespace runs
Call .split() with no arguments on line. The argument-less form treats any maximal run of whitespace (spaces, tabs, newlines) as a single delimiter, so inconsistent padding stops mattering.
Step 2: Let the default drop the empties
There is no second step. The no-argument split also discards leading, trailing, and interior empty fields, so the non-empty tokens are exactly what you return. An all-whitespace line falls out as an empty list for free.
The solution
def tokenize(line: str) -> list:
return line.split()No arguments means runs of whitespace collapse and empty tokens vanish.
- `line.split(' ')`
- On ' POST /login ' returns ['', '', 'POST', '', '', '/login', '', '']. You now own the empty-token cleanup, and tabs and newlines are not separators.
- `line.split()`
- On the same input returns ['POST', '/login']. Whitespace runs collapse, edges trim, empties drop, and tabs and newlines are handled too.
Common follow-up questions
- What if fields were separated by a single '|' instead of whitespace, and empty fields were meaningful? (Tests `.split('|')` and the need to keep or filter empty tokens deliberately.)
- What changes if a line mixes tabs and newlines into the spacing? (Confirms `.split()` already treats tabs and newlines as separators.)
- How would you tokenize while keeping the delimiters in the output? (Tests `re.split` with a capturing group to retain the separators.)