Matheion

MA-PY1 · Module 2.2

Strings and text files

Topics: Strings · Files · Encoding

Overview

Module 2.2 — Strings and text files

Scroll Core ideas → worked snippets → Practice (quiz). Attempt each question before Discuss / reveal. Use any Python REPL, script, or notebook you like.

Concepts

Core ideas — text and files

Programs spend huge effort shuffling human-readable text. Python strings are immutable sequences of Unicode code points: “editing” constructs new objects; the old one is dropped if unreferenced.

String operations you will use constantly

  • Concatenate: parts[0] + sep + parts[1] — fine for few pieces; sep.join(parts) scales (no accidental missing separators).
  • Split / strip: line.strip().split(',') parses many ad-hoc CSV-like lines. split() without args splits on arbitrary whitespace.
  • Search / test: s.startswith(prefix), s.endswith(suffix), sub in s, s.find(needle) (returns -1 when absent—contrast .index which raises ValueError).
  • Replace: s.replace(old, new) returns a new string.
  • Case: upper, lower, title—pick for protocol needs (passwords should not blindly lower-case).

f-strings — readable formatting

user = "ada"
n = 3
msg = f"{user!r} queued {n} jobs"

!r calls repr—handy for debugging. For fixed-width numbers look at format spec mini-language later ({pi:.3f}).

Files: open, process, close (automatically)

Filesystem paths are bytes on disk interpreted as characters using an encoding. On modern code bases default to encoding='utf-8' in open to avoid locale surprises on Windows.

Modes you need first:

| Mode | Meaning | |------|---------| | 'r' | read text (default) | | 'w' | write—truncates existing file on open | | 'a' | append |

Binary modes 'rb' / 'wb' bypass decoding—use for images, pickles, compressed bytes.

The with statement ensures close() even if the block errors:

with open("log.txt", encoding="utf-8") as f:
    for line in f:
        ...

Iterating for line in f reads lazily—best for big logs. read() slurps whole file; readlines() builds a Python list of lines (watch memory).

pathlib (modern path juggling)

from pathlib import Path
p = Path("data") / "scores.txt"
text = p.read_text(encoding="utf-8")   # shortcut for tiny files

Self-study checklist

  • Decide immutable implication: s += "!" inside a for reallocates repeatedly—fine for small examples; for massive text, accumulate into a list of fragments and call "".join(...) once.
  • Always state encoding explicitly in new open/Path calls intended to be portable.
  • Contrast split(',') vs split() behaviour on " a b c ".

Examples

Worked snippets — strings & files end-to-end

Join vs repeated +

words = ["the", "quick", "fox"]
print(" ".join(words))
print("-".join(words))

Avoid s = ""; for w in lst: s += w unless lists are tiny.

Parse a CSV-ish line safely

raw = "  42, 7,,  x  "
parts = [p.strip() for p in raw.strip().split(",")]
print(parts)

Note the empty field between commas.

Prefix / membership tests

path = "archive/data.csv"
print(path.endswith((".csv", ".tsv")))
print("needle" in "hayneedlestack")

f-strings and formatting

name = "Lin"
epochs = 3
accuracy = 0.912337
print(f"{name}: {epochs=} acc={accuracy:.3f}")

(Python ≥3.8 {epochs=} debug form—readable training logs.)

Read entire small file → lines

from pathlib import Path

demo = Path("sample.txt")  # you create when experimenting
lines = demo.read_text(encoding="utf-8").splitlines()
for i, line in enumerate(lines):
    print(f"{i+1:02d}| {line}")

Stream with with open — preferred for bigger files

counts = []
with open("grades.txt", encoding="utf-8") as fh:
    for line in fh:
        line = line.strip()
        if not line.startswith("#"):   # skip comments
            counts.append(line.count(","))

print(sum(counts))

Append without clobber

with open("log.txt", "a", encoding="utf-8") as log:
    log.write("event: restarted\n")

Remember w resets file length unless you consciously want that.

Path building

from pathlib import Path

base = Path("exports")
out = base / "2026" / "summary.txt"
print(out.name, out.parent)

Use / overload on Path—clearer than string concatenating slashes.

Practice check — strings and text files

Multiple-choice check from the Matheion app lesson. Pick an answer for each question, then submit.

  1. 1.What happens when you run `s = 'hello'` then `s[0] = 'H'`?

  2. 2.What does `'a,b,,c'.split(',')` return?

  3. 3.Why is `with open('log.txt') as f:` preferred over a plain `f = open('log.txt')`?

  4. 4.Opening a file with `open('out.txt', 'w')` does what to any existing content?

  5. 5.What does `' hi there '.strip()` return?