1.2.12 · D5Introduction to Programming (Python)
Question bank — String methods — upper, lower, strip, split, join, replace, find, format
True or false — justify
Every string method modifies the string it is called on.
False — strings are immutable, so each method builds and returns a brand-new string while the original is untouched.
name.strip() on its own line cleans name.
False — the cleaned copy is the return value; without
name = name.strip() that copy floats away and name is unchanged.s.upper() will convert the digits in "a1b2" to something.
False — only letters are cased;
"a1b2".upper() is "A1B2", the digits 1 and 2 are left exactly as they were.s.find(sub) returns True when sub is present.
False — it returns an index (a number). Presence gives an integer
>= 0, absence gives -1; neither is a real boolean."a b".split() and "a b".split(' ') give the same list.
False — bare
split() collapses runs and drops empties → ['a','b']; split(' ') splits on each single space → ['a','','b'].sep.join(list) puts sep after every item including the last.
False —
sep goes between items only, so an n-item list gets n-1 separators and no trailing one.s.replace("a","b") changes only the first "a".
False —
replace swaps every occurrence by default; pass a third count argument like s.replace("a","b",1) to limit it.You can call .lower() directly on the result of .strip().
True —
strip() returns a string, so chaining raw.strip().lower() just calls .lower() on that returned string." ".join([1, 2, 3]) works fine.
False —
join requires an iterable of strings; integers raise a TypeError. You must convert them (e.g. via f-strings or str()) first.s.strip("xy") removes the substring "xy" from the ends.
False — it removes any individual characters
x or y from both ends, in any order, not the literal pair "xy".Spot the error
if s.find("a"): print("found") — what's wrong?
A match at index
0 is falsy, so a string starting with "a" is wrongly reported as not found; test != -1 or use "a" in s. See Boolean truthiness.email = input().strip (no parentheses) — what happens?
Without
() you assign the method object itself, not its result, so email is a bound method, not the cleaned string — nothing gets stripped.words = sentence.split; words[0] — why does this fail?
split without () isn't called, so words is a method, not a list, and indexing it raises TypeError.s.replace("a","b") on its own line, then reading s — bug?
s still holds the old string; the replaced copy was discarded because it wasn't reassigned to a variable."a,b,c".join(",") — spot the mistake.
The roles are swapped —
join is called on the separator with the list as the argument, so it should be ",".join(["a","b","c"]).if user_input == "yes": after only calling .lower() on it without reassigning — problem?
If the code did
user_input.lower() without reassigning, user_input still has its original casing, so "YES" fails the comparison.int("3.5".strip()) to clean a number — why still crash?
strip() only removes edge whitespace, not the decimal point; int("3.5") still raises ValueError. Clean-up ≠ type conversion. See User input and validation.Why questions
Why does find return -1 instead of raising an error when absent?
-1 is a sentinel value that lets you branch with a simple if find != -1: test without wrapping every lookup in exception handling.Why must strings be immutable if it forces us to reassign?
Immutability makes strings safe to share, hashable (usable as dict keys), and predictable — no hidden method can mutate a string another part of your code is relying on.
Why prefer join over building a string with + in a loop?
join inserts separators only between items automatically and, because strings are immutable, avoids creating a fresh string on every +, so it's far faster for many pieces. See Lists.Why does bare split() suit human text but split(sep) suit structured data?
Human text has irregular spacing, so collapsing runs and dropping empties gives clean tokens; structured data (CSV) needs every separator honoured so empty fields survive as
''.Why does find rely on slicing s[i:i+m] internally?
It slides a length-
m window across the string and compares each slice to the target; slicing is how it extracts that window. See Strings — indexing and slicing.Why does format use a spec like {:.1%} instead of doing the maths yourself?
The spec separates the value from its presentation —
.1% multiplies by 100 and appends % so your logic stays clean and the formatting lives in one place.Why is the last valid start index n - m when searching a length-n string for a length-m substring?
Past index
n - m there aren't enough characters left for the substring to fit, so any later start would run off the end.Edge cases
"".split(",") — what comes out?
[''] — a list holding one empty string, because there was one (empty) field with no comma to break it." ".strip() — result?
"" — every character was whitespace, so stripping the edges consumes all of it, leaving the empty string."aaa".replace("aa","b") — how many replacements?
One — after replacing the first
"aa" you get "ba", and replace scans left-to-right without overlapping, so the result is "ba".",".join([]) on an empty list — result?
"" — with zero items there is nothing to place and no separators to insert, so you get the empty string.",".join(["solo"]) — how many separators appear?
Zero — a single item has nothing after it, and separators only go between items (
n-1 = 0)."cat".find("") — searching for the empty string?
Returns
0 — the empty string is considered to exist at the very start (and every position), so the first match is index 0."a.b.c".split(".", 1) — what does the maxsplit do?
It splits only once →
['a', 'b.c'], leaving the rest of the string intact after the first separator.Active recall
Recall Rebuild the deepest trap in one sentence
Why does calling a string method never change your variable? ::: Because strings are immutable, every method returns a new string, so unless you reassign that return value your variable keeps its old contents.
Recall The falsy-find gotcha
Why is if s.find(x): dangerous but if x in s: safe? ::: find returns 0 for a match at the start, which is falsy and misread as "absent"; the in operator returns a true boolean, so it can't be tripped by index 0.
Connections
- Yeh note Hinglish mein padho →
- Immutability in Python (the root of the reassign trap)
- Strings — indexing and slicing (why
findusess[i:i+m]) - Lists (
splitoutput,joininput) - Boolean truthiness (the falsy
0/-1trap) - f-strings (modern alternative to
.format) - User input and validation (cleaning is not converting)