1.2.12 · D3Introduction to Programming (Python)

Worked examples — String methods — upper, lower, strip, split, join, replace, find, format

1,916 words9 min readBack to topic

The scenario matrix

Before solving anything, let's map out every category of input a string method can face. A string is a row of characters indexed 0, 1, 2, …. The "surprises" come from where things sit and whether they exist at all.

Cell Scenario class The trap it hides
A Normal / happy-path text none — baseline
B Substring present at index 0 find returns 0, which is falsy
C Substring absent find returns -1, not an error
D Empty string "" or empty pieces split can produce '' entries
E Doubled / edge separators (",,", leading ,) split(sep) keeps empty pieces
F Whitespace runs vs a single space split()split(' ')
G No letters (digits/symbols only) upper/lower change nothing
H Round-trip split→join must give the original back
I Real-world word problem chaining under pressure
J Exam twistformat percent + limited replace presentation spec + count arg

The eight examples below hit all ten cells. Each is labelled with the cell(s) it covers.

Figure — String methods — upper, lower, strip, split, join, replace, find, format

Worked examples









Active recall

Recall Which cell breaks

if s.find(x):? Cell B — a match at index 0 returns 0, which is falsy. ::: Use != -1 or the in operator.

Recall How many pieces from

"a,,b".split(",")? Two commas → 2 + 1 = 3 pieces: ['a', '', 'b']. ::: The empty middle piece is cell D.

Recall Why does

" a b ".split() give length 2 but .split(' ') give more? Bare split() collapses whitespace runs and drops edge empties; split(' ') treats every single space as a hard cut. ::: Cell F.


Connections

  • Parent topic
  • Strings — indexing and slicing (find slides an s[i:i+m] window)
  • Lists (split → list, join ← list)
  • Immutability in Python (every result is a fresh string — reassign!)
  • f-strings (the modern face of .format)
  • Boolean truthiness (why 0 and -1 trap you)
  • User input and validation

Scenario Map

find

find

split sep

split none

use != -1

returns -1

keeps empties

collapses

Any string input

Match at index 0

Substring absent

Edge separators

Whitespace runs

Safe code