1.2.12 · D1Introduction to Programming (Python)

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

2,492 words11 min readBack to topic

This page assumes nothing. Before you read the parent topic, every symbol it silently uses is built here from the ground up, in an order where each idea leans only on the ones before it.


0 — What even is a string?

Picture it as a strip of paper cut into equal boxes, one character per box, laid left to right.

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

Look at the figure: the word "cat" becomes three boxes. The boxes have an orderc comes before a comes before t. That order is the whole reason we can talk about positions, which is the next symbol we need.


1 — The index (the numbers 0, 1, 2, …)

The notation s[i] means "the character in box number i of string s". We say this out loud as "s at i".

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

The figure shows "cat" with a number line under the boxes. Notice the red arrow: s[1] points at the box holding a. We will build the compound expressions the parent uses (like windows of characters) once we have slicing in section 3.

Negative indices — counting from the right


2 — Length: the symbol len(s) and |t|

The parent also writes |t| (vertical bars) — in maths those bars mean "the size of t", which for a string is exactly its length. So |t| and len(t) are the same thing; the parent just borrows the maths symbol inside its formula.


3 — Slicing: the symbol s[i:j]

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

In the figure, the teal bracket covers s[0:2] of "cat""ca" (boxes 0 and 1; box 2 is left out, marked by the dotted fence).

(Slicing gets its own full page in Strings — indexing and slicing; here we only need enough to read the parent's formulas.)


4 — Substring, and the search question s[i:i+m] == t

The parent's find slides a window and asks s[i:i+m] == t. The == here means "are these two strings exactly equal — same boxes, same order, same casing?" (Two = signs, not one; one = means assign a value, which is a different symbol entirely.)


5 — True / False and truthiness (the find trap)

But Python also lets you treat other values as if they were yes/no when they sit inside an if. This is called truthiness, and it is the reason the parent warns about find:

We build this properly in Boolean truthiness; you only need to know here that 0 is falsy and that's the whole bug.

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

The figure lines up find's possible return values on a strip: -1 (absent, but truthy), 0 (match at start, falsy — the trap!), and 1, 2, 3, … (match later, truthy). The safe test is != -1 (the plum box), which reads "the answer is not the not-found sentinel."


6 — The list [...] — what split produces

split takes one string and returns a list of strings; join takes a list of strings and returns one string. So a list is the "in-between" shape the parent moves text through. Full details live in Lists.


7 — Whitespace and the escapes \n, \t

Two of those blanks are typed with a backslash. The backslash is an escape: it tells Python "the next letter isn't literal — read it as a special character."

  • \n is one character, a newline (jump to the next line).
  • \t is one character, a tab (a wide horizontal gap used to line columns up).

So "a\nb" is a, newline, bthree boxes; and "a\tb" is a, tab, b — also three boxes.


8 — The placeholder {} and format spec {:.1%}

The colon version {:.1%} adds a format spec — a mini-recipe for how to display the value:

  • % means "multiply by 100 and add a percent sign",
  • .1 means "show 1 digit after the decimal point."

So "{:.1%}".format(0.8736) gives "87.4%". The modern replacement for this is covered in f-strings.


9 — Immutability (the idea that ties it all together)

This single fact — explored fully in Immutability in Python — is the reason the parent's biggest warning exists, and the reason all methods return rather than mutate. It's also why cleaned User input and validation always looks like x = input().strip().


Prerequisite map

String is a row of characters

Index numbers 0 1 2

Negative index from the right

Length len s

Slice s i to j

Substring and equality ==

Booleans and truthiness

Lists square brackets

Whitespace newline and tab

Placeholder and format spec

Immutability new copy

String methods toolbox


Equipment checklist

What is a string, in one sentence?
A frozen, ordered row of characters, one per box.
What index does the first character have?
0 — you step past zero boxes to reach it.
What does s[-1] give, and why is it handy?
The last character; it saves computing len(s)-1 and counts from the right.
What does len("cat") return, and what's the biggest valid index?
3, and the biggest index is 2 (that is len − 1).
What does s[i:j] give, and how long is it?
The boxes from i up to but not including j; length is j − i.
So how wide is the window s[i:i+m]?
Exactly m boxes.
What does "hello"[2:10] return — error or value?
'llo' — slicing clamps to the end, it never errors.
What does == ask that = does not?
== asks "are these equal?" (answer True/False); = stores a value.
Is 0 truthy or falsy? Is -1?
0 is falsy; -1 is truthy — that's the find trap.
What safe test replaces if s.find(x):?
if s.find(x) != -1: (or if x in s:).
What shape does split return, and join consume?
A list of strings; join consumes a list and returns one string.
How many characters is "\n"? And "\t"?
One each — a single newline box and a single tab box.
What does {:.1%} do to 0.5?
Shows it as 50.0% (×100, one decimal, percent sign).
Why must you write name = name.strip() and not just name.strip()?
Strings are immutable; strip returns a new copy, and only reassignment keeps it.

Connections

  • Parent topic
  • Strings — indexing and slicing (index and slice built here in full)
  • Lists (the shape split returns / join consumes)
  • Immutability in Python (why methods copy, never edit)
  • Boolean truthiness (why 0/-1 traps find)
  • f-strings (modern successor to {} / .format)
  • User input and validation (where messy strings come from)