Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 6 · Lesson 2 · Core

Turning lines of text into data

Strip, split and convert each line so a total or an average can be worked out.

  • 50 minutes
  • Serves O4
  • Assumes M6.L1

Phase 1: Prepare

Step 1 Warm-up recall

From M6.L1: what does mode "a" do?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • use strip and split on a line (Foundation);
  • convert text to numbers with int and float (Core);
  • total a column from a file (Core).

Phase 2: Teach

Step 3 A familiar example

A payroll clerk reads a line that says Ann,70 and must treat 70 as a number, not as the letters seven and zero. A program must make the same conversion.

Step 4 Clear explanation

Everything read from a file is text, including digits. To calculate, convert it.

total = 0
count = 0
with open("scores.txt") as f:
    for line in f:
        parts = line.strip().split(",")
        total = total + int(parts[1])
        count = count + 1
print(total, count)
print(total / count)
155 2
77.5
Line"Ann,70\n"stripremove newlinesplit["Ann","70"]int70
Each line of a data file is text. Strip the newline, split on the separator and convert numbers before you use them.

split(",") cuts a line at each comma and gives a list. int("70") gives the number 70, and float handles decimals. Without the conversion, "70" + "85" joins text to give "7085" instead of adding.

Always count the rows you used, as in Module 4, and compare with the rows in the file. If a line is blank or has the wrong number of parts, the program stops with an IndexError or a ValueError. The next lessons deal with these cases.

Step 5 Worked example (4 marks)

The line is "Cy,60\n". Give the value of int(line.strip().split(",")[1]) + 5.

  1. strip removes the newline: Cy,60. (1 mark)
  2. split gives ["Cy", "60"]. (1 mark)
  3. Item 1 is "60"; int makes it 60. (1 mark)
  4. 60 + 5 = 65. (1 mark)

Go deeper: the professor's notes

Check that the count of rows out matches the count in. Differences are where errors hide.
In

Rows read.

Used

Good rows.

Skipped

Reported.

Readrows inCheckeach rowCountused and skippedComparein = out
Count check

Check

InUsedSkipped
1082

At work: A sales file

A file has bad lines.

  1. Count the lines read.
  2. Report each skipped line.

What a careful practitioner decides. Do not skip rows silently.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. "a,b,c".split(",") gives:

2. int("42") gives:

3. Adding "3" + "4" as text gives:

4. int("abc") gives:

Phase 4: Close

Step 7 Recap

  • File data arrives as text.
  • strip then split then int turns a line into values.
  • Count the rows you used and compare with the file.

Step 8 Exit ticket (ungraded)

For the line "Dee,90", write the code that gets the score as a number.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write a program that finds the highest score in scores.txt and prints the name.

In industry: The index that lost half its value

In January 1982 the Vancouver Stock Exchange started an index at 1000. After each update the value was cut off at three decimal places instead of rounded. About 3,000 updates a day added up, and by November 1983 the index read 524.811 when the correct figure was 1098.892.

Link to this lesson. Small errors in how data is stored can add up across thousands of operations; check totals against an independent calculation.

Source: Wikipedia, Vancouver Stock Exchange, citing the Toronto Star (29 November 1983)

Common mistakes

MistakeWhy it fails
Adding text instead of numbersConvert with int or float.
Wrong column numberThe first column is 0.
Not counting rowsCompare the count with the file.

Limits. Fields that contain commas inside quotes need the csv module, which the next lesson introduces.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · Why must you never open your only copy with w?
Open wemptyCrashnothing leftFixnew file
Overwrite

The file is emptied at once, before anything is written. If the program then fails, the data is gone. Write to a new file instead.

Card 2 of 3 · What does strip do to a line?
Linewith newlinestripcleanNextsplit
strip

It removes the newline and spaces at the ends, so a line read as "Ann,70\n" becomes "Ann,70".

Card 3 of 3 · What does split do?
Lineone textsplitpartsListof text
split

It cuts a line at a separator into a list: "Ann,70".split(",") gives ["Ann", "70"]. A comma is the usual separator in data files.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards