Learning outcomes
By the end of this chapter, you should be able to:- use important string methods
- split and join text data
- format output cleanly
- solve basic string problems
30-minute recording plan
0-8 min: core string methods8-13 min:find()andcount()traps13-20 min:split()andjoin()usage20-25 min: string formatting patterns25-30 min: pattern questions (palindrome/frequency)
Common string methods
lower()/upper()for normalizationstrip()for cleaning extra spacescount()for frequency checksfind()for position lookup (-1if missing)replace()for controlled substitution
Beginner alert: find() trap
find() returns index, not True/False.
Split and join
split() is useful for parsing input data.join() is useful for rebuilding text in a chosen format.
split(",") splits only on commas.
If you write split() with no argument, it splits on spaces/tabs/newlines.
Method chaining: return type tracker (MCQ-critical)
Always read chained expressions left to right and track type after each step. Common string method return types:- returns
str:lower(),upper(),strip(),replace(old, new),join(iterable) - returns
list:split() - returns
bool:startswith(prefix),endswith(suffix),isalpha() - returns
int:find(sub),index(sub)(butindexraises error if missing)
Solved type/exceptions set (Q11-Q18 style)
s[:3].upper().split()->lists.startswith()-> raisesTypeError(missing requiredprefix)s.startswith("hello")->bools.lowercase().isalpha()-> raisesAttributeError(lowercasedoes not exist; correct islower)s.isalpha().upper()-> raisesAttributeError(isalpha()returnsbool, andboolhas noupper)s.replace('h').index("3")-> raisesTypeError(replaceneedsoldandnew)s.join(s.split('-'))->strs.join(s[0], s[1], s[3])-> raisesTypeError(joinexpects one iterable argument)
- if
sis shorter than 4 characters,s[3]can raiseIndexErrorbeforejoinruns.
Two high-frequency traps
- Calling a method with missing required parameters causes
TypeError. - Using a wrong method name (like
lowercase) causesAttributeError.
String formatting
Format specifier mini-guide (MCQ-critical)
In an f-string, this form is very common:f"{value:06}"
- total width =
6 - pad with leading zeros if needed
:<9left align in width 9:>9right align in width 9:^9center align in width 9:9for strings behaves like left align by default
Solved exam-style case
a*3->"555"then:9->"555 "b*5->"66666"then:^9->" 66666 "a*7->"5555555"then:>9->" 5555555"
Quiz trap: strings equal to "000500"
Basic pattern problems
Palindrome check
Frequency of characters
Code-trace trap: condition is narrower than it looks
- it checks only first character is lowercase
- it checks first and last characters are equal
- it does not check every character is lowercase
tacit->Truetrumpet->Trueease->TrueTrumpeT->False(first char uppercase)
- empty input can raise
IndexErroratword[0]
Mini showcase: parse a CSV-style score line
Exam-focused points
strip()removes leading/trailing spaces onlyfind()returns-1if not foundsplit()output type is list- f-strings are preferred for readable output
f"{500:06}"means zero-pad to width 6, giving"000500"- for string formatting width,
:9is left,:^9center, and:>9right - in method chains, track intermediate types (
str->list-> etc.) before choosing answer
Practice questions
- Count vowels in a string.
- Replace all spaces with
_. - Check whether two strings are anagrams (basic approach).
