Lesson · Strings & Text
String API
60 min readString API
Python's string API provides composable operations for cleaning, splitting, searching, replacing, and normalizing text. The best solutions usually combine a few clear operations rather than one clever expression.
Learning goals
- Chain
strip,split, andjointo take a delimited line apart and rebuild it in a new shape. - Choose between
findandindexbased on whether a missing match should return a sentinel or raise. - Replace whole groups of
orcomparisons withstartswithandendswithgiven a tuple. - Say when
casefoldis required instead oflowerfor caseless comparison. - Predict what each method returns, and confirm that none of them edits the receiver in place.
Mental model
Every method returns a result and leaves the text it was called on untouched, so a pipeline is a chain of new strings rather than a sequence of edits. join is split in reverse with the receiver meaning switched, and the search methods differ only in how a miss behaves.
A pipeline of new strings
the method receiver is never edited
Mental model
the same mechanism as a compact list
clean the edges raw.strip() (returns new text)
↓ cut into pieces? raw.split(",") (list of parts)
↓ rebuild text? " | ".join(parts) (the separator is the receiver)
↓ only need a spot? find gives -1; index raises
↓ compare caseless? casefold() ("Straße" folds to "strasse")Core idea
The string API is a set of small operations that compose because each one returns a value and leaves its receiver alone, so raw.strip().split(",") reads left to right as clean, then cut. Two decisions recur across the lesson: a search either reports a position (find, with -1 for a miss) or enforces one (index, raising ValueError), and case handling separates display (lower, upper) from comparison (casefold, which folds ß to ss). Replacing text follows the same rule as everything else: replace returns new text, and the original stays put.
strip
strip removes selected leading and trailing characters, whitespace by default. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
split
split separates text into pieces using whitespace or a chosen delimiter. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
join
join combines an iterable of strings using the receiver as the separator. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
replace
replace returns new text with selected substrings replaced. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
find
find returns the lowest matching substring index or -1 when no match exists. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
index
index returns a matching index but raises an exception when no match exists. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
startswith
startswith checks whether text begins with a prefix or one of several prefixes. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
endswith
endswith checks whether text ends with a suffix or one of several suffixes. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
lower
lower returns a lowercase-oriented Unicode transformation. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
upper
upper returns an uppercase-oriented Unicode transformation. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
casefold
casefold performs an aggressive Unicode case normalization intended for caseless comparison. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
Character-testing helpers
Methods such as isalpha, isdigit, isalnum, and isspace use Unicode-aware character properties. They can accept more characters than ASCII-only rules.
Walkthrough
raw.strip()removes the outer spaces and.split(",")cuts the rest on each comma, so the comprehension's per-piecename.strip()is what buildsnames = ['Ada', 'Grace', 'Guido']." | ".join(names)puts the glue on the receiver and the pieces in the call, producingAda | Grace | Guido;joinissplitin reverse with the receiver roles switched.- The last two lines copy in two styles:
replacereturns new text with only the match swapped, so the leading spaces ofrawsurvive, andcasefoldfoldsßtoss, which makes the"Straße"comparison printTrue. - Predict before running: the
nameslist, the joined line, whetherrawchanged, and the casefold boolean.
Experiments to try
- Compare
"a,,b".split(",")with" a b ".split(); one keeps the empty piece between commas, the other collapses whitespace runs, and the argument you pass selects the behavior. - Call
findandindexfor a substring that is not present and record-1against theValueError; decide which contract fits a conditional and which fits a required match. - Run
",".join(["a", 1])and read theTypeError; repair it by converting the item withstr()before the call. - Test
"report.csv".endswith((".csv", ".txt"))and"report.csv".startswith(("log", "report")); one tuple replaces a chain oforchecks in a single call.
Common mistakes
- Expecting
stripto clean inner text: it removes only from the ends, so" a b ".strip()keeps the double space in the middle, and cleaning fields needssplit,replace, or both. - Using a missed
findas a position:findreturns-1on failure, and-1is also a valid negative index, so the miss silently becomes a read from the end of the string;indexwould have raised instead. - Joining non-strings:
",".join([1, 2])raisesTypeErrorbecausejoinaccepts onlystritems, so convert each piece before the call, not after it fails. - Assuming
loweris enough for caseless comparison:"Straße".lower() != "STRASSE".lower(), whilecasefoldfolds theßand matches them.
Practice: Easy
- Run the first two lines of the worked example in the REPL and print
rawandnames; state which calls ate the spaces and which object still holds them. - Call
"Ada".find("x")and"Ada".index("x"); record both outcomes and choose which one you would use inside anifcondition. - Build
"a-b-c"with"-".join(["a", "b", "c"])and take it apart again with.split("-"); confirm the round trip and that the original list never changed.
Practice: Medium
- Clean
" Ada , Grace,Guido "into['Ada', 'Grace', 'Guido']with a strip/split pipeline, then rebuild it with a different separator and one more transform of your choice. - Replace an extension check written as three
orcomparisons withendswith((".csv", ".txt", ".md")); run both forms on the same filenames and compare readability. - Take
"Straße"throughlower,upper, andcasefold; record the three results and explain which pair of calls implements a correct caseless comparison.
Practice: Hard
- Design a label normalizer: trim a raw string, split it on commas, strip each piece, normalize case for comparison, and join it back with a canonical separator. Define the expected output for messy inputs such as empty pieces and mixed case, and one test, before implementing.
- Build a failure lab with three cases: a missed
findused as an index,joinover a mixed-type list, and a caseless comparison written withlowerwherecasefoldis required; explain the mechanism behind each. - Connect this lesson to the formatting lesson: explain why a cleaned list of strings feeds naturally into
joinor an f-string, and how a formatting template and ajoindiffer in what they let you control.
Lesson checklist
- I can chain
strip,split, andjointo reshape a line of text and say what each call returns. - I can choose between
findandindexbased on how a missing match should behave. - I can test several prefixes or suffixes with one tuple argument.
- I can pick
casefoldfor comparison andlowerfor display, and explain the difference.
Remember
The string API composes because every method returns a result and leaves the receiver alone: `strip` cleans the edges, `split` and `join` convert between text and lists with the receiver playing opposite roles, and `replace` builds new text rather than editing the old. The repeated decisions are how a miss should behave (`find` reports, `index` raises) and how case should fold (`lower` for display, `casefold` for comparison), and `startswith`/`endswith` accept tuples to replace chains of `or` checks.
Interview angles
What is the main purpose of **strip**?+
strip removes selected leading and trailing characters, whitespace by default. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
What should you pay attention to when using **split**?+
split separates text into pieces using whitespace or a chosen delimiter. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
How does **join** fit into this lesson?+
join combines an iterable of strings using the receiver as the separator. In String API, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
Why can a missed `find` be more dangerous than a missed `index`?+
find returns -1, and -1 is also a valid negative index, so using the result in a slice or index silently reads from the end instead of reporting the miss. index raises ValueError at the moment of the miss, which keeps the failure visible.