01 / 20

Parsing
Structured Text

Learn how to read CSV-like data with Python: splitting lines into fields, converting types, and building structured records from raw text.

Python

What is Structured Text?

Structured text is data stored in a consistent, repeating pattern. Each line follows the same format: values separated by a specific character called a delimiter. The most common example is a CSV file (Comma-Separated Values).

name,age,grade Alice,17,11 Bob,16,10 Carol,18,12

Key Vocabulary

Delimiter
The character that separates fields. Commas, tabs, and pipes are common.
Field
A single value in a record, like a name or a number.
Record
One complete row of data: all the fields on a single line.

Why Parse Structured Text?

Raw text files are everywhere: spreadsheet exports, sensor logs, web API responses, and database dumps. To do anything useful with this data in Python, you need to break each line into individual values you can work with.

Analyze
Compute averages, find maximums, or count occurrences.
Filter
Select only records that match certain criteria.
Transform
Convert data into a different format or structure.

The Core Method: .split()

Python's .split() method breaks a string into a list of substrings at each occurrence of the delimiter you specify.

line = "Alice,17,11" fields = line.split(",") print(fields) # ['Alice', '17', '11']

Anatomy of a Parse

"Alice,17,11" Raw string .split(",") 'Alice' '17' '11' List of strings int() int() 'Alice' 17 11 Typed values Build record {"name": "Alice", "age": 17, "grade": 11} Dict

.split() vs .strip()

These two methods do very different things, but you almost always use them together. Don't confuse them:

.split(sep) .strip()
Purpose Break string into a list at each sep Remove leading/trailing whitespace
Returns list string
Example "a,b".split(",") → ['a','b'] " hi\n".strip() → 'hi'
When to use Separating fields Cleaning each field or line

How to Parse a CSV File

1
Open the file with open() and read it line by line.
2
Strip whitespace from each line using .strip().
3
Skip the header row (or use it to name your fields).
4
Split each line on the delimiter using .split(",").
5
Convert types: use int() or float() on numeric fields.
6
Store the record in a list of lists, list of dicts, or other structure.

Example 1: Basic Parse

Given the file students.csv with this content:

name,age,grade Alice,17,11 Bob,16,10 Carol,18,12
records = [] with open("students.csv") as f: header = f.readline().strip().split(",") for line in f: fields = line.strip().split(",") records.append(fields) print(header) # ['name', 'age', 'grade'] print(records) # [['Alice','17','11'], ['Bob','16','10'], ...]

Example 2: Type Conversion

Now we convert each record into a dictionary with proper types:

students = [] with open("students.csv") as f: f.readline() # skip header for line in f: name, age_str, grade_str = line.strip().split(",") students.append({ "name": name, "age": int(age_str), "grade": int(grade_str) }) print(students[0]["age"] + 1) # 18 (math works!)

Example 3: Tab-Delimited Data

Not all files use commas. Some use tabs (\t) or pipes (|). Just change the delimiter in .split():

# File: temps.tsv (tab-separated) # city\thigh\tlow # Portland\t58.3\t42.1 temps = [] with open("temps.tsv") as f: f.readline() # skip header for line in f: city, high, low = line.strip().split("\t") temps.append({ "city": city, "high": float(high), "low": float(low) })

Building a Reusable Parser

Wrap the parsing logic in a function so you can reuse it with any file and delimiter:

def parse_csv(filename, delimiter=","): records = [] with open(filename) as f: headers = f.readline().strip().split(delimiter) for line in f: values = line.strip().split(delimiter) record = dict(zip(headers, values)) records.append(record) return records data = parse_csv("students.csv") # [{'name':'Alice','age':'17','grade':'11'}, ...]

Processing After Parsing

Once you have a list of records, you can filter, compute, and report:

# Find all juniors (grade 11) juniors = [s for s in students if s["grade"] == 11] # Average age of all students avg_age = sum(s["age"] for s in students) / len(students) # Names only names = [s["name"] for s in students]

Common Mistakes

✕ Forgetting .strip()
Lines from files end with \n. Without .strip(), your last field will have a hidden newline character.
✕ Not converting types
After .split(), everything is a string. "17" + "11" gives "1711", not 28.
✕ Wrong delimiter
Using .split(",") on tab-separated data returns the entire line as one field.

Parsing Cheat Sheet

Method Input Output Purpose
.strip() " hi\n" "hi" Clean whitespace
.split(",") "a,b,c" ['a','b','c'] Separate fields
int() "17" 17 String to integer
float() "3.14" 3.14 String to decimal
zip() headers, values paired tuples Match header to value

Question 1 of 5

What does "a,b,c".split(",") return?

Question 2 of 5

After splitting "Alice,17,11" on ",", what is the type of the second element?

Question 3 of 5

Which line of code correctly removes the trailing newline and splits on commas?

Question 4 of 5

Consider this file scores.csv. You want to compute the average score.

player,score Maya,95.5 Jayden,88.0 Priya,91.2

Which conversion function should you use on the score field?

Question 5 of 5

Given this code:

line = "Portland\t58.3\t42.1" parts = line.split(",") print(len(parts))

What will print(len(parts)) output?