Reading — step 1 of 8
Learn
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:
msg.upper() is a method called on msg. The string itself is the (implicit) first argument.
Case methods
Almost always you want .lower() for case-insensitive comparisons:
Cleaning whitespace
strip() is essential for messy input — it removes whitespace from both ends:
You can pass characters to strip:
Searching
Prefer find when "not found" is acceptable. Use index when missing is exceptional.
Replacing
Splitting and joining — text ↔ list
Two of the most-used methods:
Notice join is called on the SEPARATOR, not the list. Counter-intuitive but that's the API.
Checking content
Note that empty strings return False for these — there's no characters to satisfy the predicate.
Padding and alignment
Method chaining
Because every method returns a new string, you can chain:
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 changes. You must reassign:s = s.upper(). - Calling join with the wrong receiver:
["a", "b"].join(",")is a TypeError. It's",".join(["a", "b"]). - Using
findand 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
replaceand not assigning:text.replace("a", "b")returns the new string but doesn't changetext.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…