Skip to content
String Methods
step 1/8

Reading — step 1 of 8

Learn

~3 min readWorking with Text

Every string in Python comes with a toolbox of built-in methods — functions attached to the string itself. They handle the text-processing tasks you'll face daily: cleaning messy input, searching for substrings, splitting text apart, joining lists back into text, and changing case. Because strings are immutable, every string method returns a NEW string — the original is never modified.

Calling a method

Method calls use dot notation:

python

msg.upper() is a method called on msg. The string itself is the (implicit) first argument.

Case methods

python

Almost always you want .lower() for case-insensitive comparisons:

python

Cleaning whitespace

strip() is essential for messy input — it removes whitespace from both ends:

python

You can pass characters to strip:

python

Searching

python

Prefer find when "not found" is acceptable. Use index when missing is exceptional.

Replacing

python

Splitting and joining — text ↔ list

Two of the most-used methods:

python

Notice join is called on the SEPARATOR, not the list. Counter-intuitive but that's the API.

Checking content

python

Note that empty strings return False for these — there's no characters to satisfy the predicate.

Padding and alignment

python

Method chaining

Because every method returns a new string, you can chain:

python

Method chains read like a pipeline. Don't go wild — 3-4 chained methods is plenty for readability.

Common mistakes

  • Forgetting that strings are immutable: s.upper() doesn't change s. You must reassign: s = s.upper().
  • Calling join with the wrong receiver: ["a", "b"].join(",") is a TypeError. It's ",".join(["a", "b"]).
  • Using find and forgetting -1: if "x".find("y"): is True for any non-zero find result, INCLUDING -1 (not found). Compare explicitly: if s.find("y") != -1:.
  • Using replace and not assigning: text.replace("a", "b") returns the new string but doesn't change text.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…