5 · Strings: slicing, methods & f-strings
Indexing, slicing with strides, the ten methods you'll use every day, and f-string format specs for training logs.
Strings are immutable sequences — every method returns a *new* string, it never modifies the original.
Without this:
Without clean string skills, reading a CSV header, logging a training metric, or parsing a model config file all become fragile one-offs.
A Python string is an immutable sequence of Unicode characters. You can index it like a list, slice it, iterate it, and call methods on it — but you cannot change a character in place. Every operation that 'transforms' a string secretly creates a new one.
Python (in browser)
Negative indices count from the end. The slice `s[a:b]` is half-open: it includes index `a` but excludes `b`.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
Python (in browser)
`.split()` with no argument splits on any whitespace run and discards empty tokens — handy for messy log lines.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
Python (in browser)
These format specs are what real training loops use. `loss:.4f` is the single most common one.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
What does `'hello world'.split()` return compared to `'hello world'.split(',')`?
Apply what you just learned: strip, uppercase, count words, and reverse a string — all in the Arena.
- Strings are immutable — call `.strip()`, `.lower()`, `.replace()` but always capture the return value.
- `s[start:stop:step]` is a general slice; `s[::-1]` reverses; negative indices count from the end.
- f-string format specs (`:.4f`, `:3d`, `:>10`, `:,`) turn raw numbers into readable training logs.
NLP pipelines call `.lower().strip()` on every raw text sample before tokenization. CSV headers use `.split(',')` to extract column names. Training logs rely on `f"epoch={e:3d} loss={l:.4f}"` so metrics line up visually across epochs and are easy to `grep`.
If you remove it: A label like `' Dog '` (with spaces) fails a dictionary lookup against `'Dog'` — mislabeled samples silently drop from your training set without a single error message.