Python Chapter 5 — strings and text files

← Index · Solutions

Priority key · Priorities guide emphasis; they do not remove taught scope.

Exam recall

Strings are immutable. Slice stop is excluded. Read text → parse → convert → process → write; w truncates and write() adds no newline automatically.

Strings are immutable sequences priority/high

String:     C  O  M  P  U  T  I  N  G
Index:      0  1  2  3  4  5  6  7  8
Negative:  -9 -8 -7 -6 -5 -4 -3 -2 -1
s[1:4]:        O  M  P           stop index4 is excluded

Indexing asks for one position; slicing asks for a sequence of positions. That explains why an out-of-range index fails while a slice can stop at the string’s end without an error. A returned slice or case-converted string is a new value: reassign the name if you want to retain it.

For a string s, s[0] is the first character and s[-1] the last; indexing an empty string fails. s[start:stop:step] slices with an excluded stop. Slices can be empty and tolerate bounds beyond the string. s[::-1] reverses it. Strings cannot be modified by assigning to an index; construct a new string instead.

OperationMeaning / trap
len(s)Number of characters in the Python string, not necessarily encoded byte count.
s.lower(), s.upper()Return new strings; do not change s.
s.strip()Removes whitespace at both ends, not inside.
s.split(",")Splits on commas; empty fields are retained.
s.split()Splits on runs of whitespace.
",".join(parts)Joins string elements with commas.
s.find(part)First matching position or −1; position 0 is a successful match.
s.replace(old, new)Returns a string with substitutions.

Lexicographic comparison examines corresponding characters, so numeric strings do not necessarily sort numerically: "10" < "2" is True. Compare converted numbers if numeric order is intended. isdigit() accepts more than ASCII 0–9; if the specification permits only those ten characters, test against "0123456789" explicitly.

Text files priority/high

A text-file problem has three separate transformations: read a line as text → parse/convert its fields → compute or write the required result. A digit character in a file is not automatically a Python integer. Likewise, writing an integer requires converting or formatting it as text.

open(path, "r", encoding="utf-8") reads; "w" creates/truncates; "a" appends. A with block closes the file even when an exception occurs. Reading the wrong path or converting malformed data can raise exceptions; handle them only as the specification requires.

Iteration yields lines, usually with their newline. read() returns the remaining text; readline() returns one line or "" at end-of-file; readlines() returns a list of remaining lines. write() does not automatically add a newline. Use rstrip("\n") when you only want to remove newline characters; strip() also removes potentially meaningful surrounding spaces.

Do not remove the final character with line[:-1] merely to discard a newline: the last line may not have one. Distinguish the in-memory string from a path naming a file.

Remove only the characters the format permits you to remove. strip() is useful for testing blank lines, but assigning its result to a name field could remove meaningful leading/trailing spaces. State the file-format assumptions before choosing a parsing shortcut.

Worked example — original priority/high

Input file contains unquoted name,score records, no header. Ignore blank lines and return names with scores at least 50. Commas cannot occur inside names under this simple format.

def passing_names(path):
    result = []
    with open(path, "r", encoding="utf-8") as source:
        for line in source:
            if line.strip() == "":  # Skip blank records before unpacking fields.
                continue
            name, score_text = line.rstrip("\n").split(",")  # Exactly two fields.
            if int(score_text) >= 50:  # Compare numeric scores, not text order.
                result.append(name)
    return result

For Ali,50 then Bea,49, only Ali is appended. The string-to-integer conversion enables numeric comparison. For general CSV with quoted commas, use a proper CSV parser; this worked example deliberately states a simpler input format.

Practice

Exam focus: strings, conversion and slicing support HCI 2025 Q4’s identifier validation; file handling is included from school Python Chapter 5. A standalone file-processing question was not established in the selected promo set, so its priority comes from the taught scope rather than invented recurrence.

Handwritten approach: record input format/header/blank-line rules → pick read mode → parse fields → convert only numeric quantities → process → write exact separators/newlines. Test the last line without a newline and an empty file when permitted.

16A — original. With s = "COMPUTING", evaluate s[1:4], s[-3:] and s[::2]. Write count_vowels(text) counting A/E/I/O/U case-insensitively without modifying the input.

16B — original. Write write_totals(source_path, output_path). The source contains one integer per nonblank line. Ignore blank lines and write the sum followed by a newline to output_path, replacing any previous output. Assume all nonblank lines are valid integers. State the result for an empty source.

Revision checklist

  • 16.1 Index, slice and traverse strings, including negative indexes and slice steps.
  • 16.2 Explain string immutability and build a new result when modifying text.
  • 16.3 Use the taught search, case, classification, split, strip, join and replacement operations.
  • 16.4 Distinguish a textual identifier from an integer and preserve leading zeroes.
  • 16.5 Read whole files, individual lines and sequences of lines appropriately.
  • 16.6 Write and append text with correct modes and line separators.
  • 16.7 Parse delimited records and convert fields to suitable types.
  • 16.8 Process an empty file, blank lines and malformed input as required.
  • 16.9 Use context management or close files appropriately.
  • 16.10 Write a complete read-process-write solution and check the saved output.

Visual revision mindmap

Chapter 16 revision mindmap

Open this mindmap and its text version · All 21 mindmaps

Your mindmap framework

Centre: Python Chapter 5 — strings and text files. Build the six branches below. For each subbranch, add a short definition, a labelled sample and one exam trap from memory; then check the chapter.

flowchart LR
    C["16 • Revision map"]
    C --> B0["String model"]
    C --> B1["String operations"]
    C --> B2["Representation and comparison"]
    C --> B3["File interface"]
    C --> B4["Read-process-write"]
    C --> B5["Visual checks and mistakes"]
  • String model

    • Immutable sequence of characters.
    • Positive and negative indices.
    • Slice start/stop/step; stop excluded.
    • Index out of range versus forgiving slice bounds.
  • String operations

    • Case conversion and replacement return new values.
    • find: position 0 succeeds; −1 absent.
    • split with separator versus whitespace split.
    • strip/rstrip and join; retain meaningful spaces.
  • Representation and comparison

    • Text identifier preserves leading zeroes.
    • Lexicographic versus numeric order.
    • ord/chr and character processing.
    • isdigit is broader than ASCII digits.
  • File interface

    • r reads; w creates/truncates; a appends.
    • read, readline and readlines.
    • Empty string at EOF versus blank line.
    • with closes file; write needs explicit newline.
  • Read-process-write

    • Establish format, header and delimiter rules.
    • Skip only permitted blank records.
    • Parse text and convert numeric fields.
    • Accumulate result; format and save exact output.
  • Visual checks and mistakes

    • Draw file line → fields → values → result → output line.
    • Mark string indices under COMPUTING.
    • Test empty file and final line without newline.
    • Avoid: line[:-1] blindly; split comma for unrestricted quoted CSV.

Close the notes and test the map: explain one branch aloud, sketch its sample, then answer a linked practice question. Mark any missing link to revisit.

Source trail

9569 §§1.2.2,2.1.7; school Strings and Text Files.

School Tutorial 5; HCI 2025 Q4 integrates string validation.

Source guide records provenance and original-paper locations.