Every expense in your tracker is a dictionary you typed by hand. This lesson has your program read its expenses from lines of text instead, the way real data arrives. Your report stays exactly the same.
The concept
Here is your tracker as the last lesson left it. Run it:
Every record in your expenses list is Python code, braces and all. Real data rarely arrives like that. It arrives as text: a file, a form, a message from your bank. On your own computer, that text would usually sit in a file. The sandbox has no files, so a string stands in for one. Run this:
The first three lines of output come from one string. Three double quotes open it and three more close it, so it can run over several lines. This is a triple-quoted string. The line breaks you typed are part of its text.
splitlines() gave back a list with one string for each line. Like append, it is a method, written after a value and a dot. It belongs to strings, so it is a string method.
Now take one line apart. Run this:
split(",") cut the line at every comma and gave back a list of three parts. The commas are gone, but ' Transport' and ' 1500' start with the space that followed each comma.
strip() gives back the text without the spaces at its start and end. lower() gives back the text in lowercase. raw.strip().lower() runs left to right, so the result is 'transport', a key your category_budgets has. The single quotes around each printed value only show where it starts and ends.
Now look at the last line. raw still has its space and its capital. This trips up almost everyone: a string method never changes the string you call it on. It gives back a new string, and you store that. You met this rule in the type-conversion lesson, where int(fuel) on its own line changed nothing.
The syntax
lines = text.splitlines()
parts = text.split(",")
clean = text.strip()
small = text.lower()"""opens a triple-quoted string and another"""closes it. Line breaks between them are part of the text.splitlines()gives back a list with one string for each line.split(",")gives back a list of the pieces between the commas, without the commas.strip()gives back the text without spaces at the start and end. Spaces between words stay, soBus farekeeps its space.lower()gives back the text in lowercase. People typeFood,foodandFOODfor the same thing, but to Python they are three different keys.
Each one gives back something new and leaves the original alone, so store the result: category = category.strip(). That is the opposite of append, which changes its list and gives back nothing.
Methods can follow one another, as in parts[1].strip().lower(). Each dot works on what the step before it gave back. int accepts spaces around digits anyway, but stripping the amount too keeps one habit for every part.
A minimal working example
receipt_text = """Bus fare, Transport, 1500
Lunch, Food, 2500"""
for line in receipt_text.splitlines():
parts = line.split(",")
item = parts[0].strip()
category = parts[1].strip().lower()
amount = int(parts[2].strip())
print(f"{item} ({category}): ₦{amount:,}")Output: Bus fare (transport): ₦1,500, then Lunch (food): ₦2,500. In your tracker, the same loop builds a record from each line instead of printing it.
Common mistakes
You forget strip. Run this:
KeyError: ' transport'There is a space inside the quotes, before transport. Your key has no space, and a key must match exactly. A KeyError whose key starts with a space means a missing .strip().
You forget lower. You write category = parts[1].strip(). The category keeps its capital letter from the text, so looking it up in category_budgets fails.
KeyError: 'Transport'Your budget keys are lowercase, and Python treats T and t as different letters. You will see this one on purpose in Try it yourself.
You call a method but do not store the result. Run this:
It prints ' Transport', space and capital intact, with no error to warn you. category.strip() made a clean copy, and nothing kept it. Write category = category.strip().lower() instead.
A line has too few commas. Run this:
IndexError: list index out of rangeThe printed list has two parts, because the line has one comma. parts[2] asks for a third part that does not exist. Each line needs a comma after the item and another after the category.
Try it yourself
You will replace your hand-typed records with receipt text that your program reads.
-
Run the starting code below. Note your
Total spentandBy categorylines. Your report should end this lesson exactly the same. -
Directly above your
fuel_receiptline, add this, then a blank line:receipt_text = """Bus fare, Transport, 1500 Lunch, Food, 2500 Data bundle, Data, 3500 Suya, Food, 800 Fuel, Transport, 4200"""If you changed your expenses earlier, write yours instead. Use one line per record, in the same order, as item, category, amount. Start each category with a capital letter, as above, because step 5 relies on it. Run it. Confirm your report has not changed. Nothing reads the text yet.
-
Delete the lines that typed your expenses by hand:
fuel_receipt,fuel, the wholeexpenses = [list to its], and theexpenses.appendline under it. Your fuel amount now lives in your text. In their place, add:expenses = [] for line in receipt_text.splitlines(): parts = line.split(",") item = parts[0].strip() category = parts[1].strip().lower() amount = int(parts[2].strip()) expenses.append({"item": item, "category": category, "amount": amount})Run it. Confirm your report looks the same as in step 1, with the same
Total spentandBy categorylines. -
Make one line of your receipt text untidy: write its category in all capitals, with a space before the comma after it. For example,
Lunch, FOOD , 2500. Run it. Confirm your report has not changed, becausestripandlowercleaned the category. Then put the line back as it was. -
Break it on purpose: in your new loop, change
category = parts[1].strip().lower()tocategory = parts[1].strip(). Run it. Confirm the report prints as far asBy category:, then stops with aKeyErrornaming your first category with its capital letter. With the expenses given, that isKeyError: 'Transport'. -
Fix it: put
.lower()back after.strip(). Run it. Confirm yourBy categorylines return and your report matches step 1.
Your tracker now reads its expenses from text, and cleans every part before using it. Every line so far has been readable, though. The next lesson handles a receipt line that cannot be read at all, without losing the rest of your report.