Question presented to candidate: "You get messy text from a CSV export or a user form. Which string methods do you reach for to clean it, split it, search it and put it back together, and what are the traps in them?"
What a strong answer should cover:
- Strings are immutable: every method returns a new string, so you must use the return value (
s.strip()alone does nothing tos). - The cleaning and splitting core:
strip/lstrip/rstrip,split(with and without an argument,maxsplit),rsplit,partition,splitlines, andsep.join(iterable)as the inverse ofsplit. - Searching and testing:
in,find(returns -1) versusindex(raisesValueError),count,startswith/endswithwith a tuple, and theisdecimal/isdigit/isnumericdifferences. - The
strip(chars)trap β the argument is a set of characters β andremoveprefix/removesuffix(Python 3.9, PEP 616) as the fix. - Case handling:
lowerversuscasefoldfor caseless comparison;title()surprises; padding withzfill,center,ljust,rjust;translatefor many single-character replacements. - Building strings with
"".join(parts)rather than+=in a loop, and why (CPython has an in-place shortcut, but it is not guaranteed).
Code / implementation expected: Optional β a short cleaning snippet (strip, split, join) is enough; bonus for showing the rstrip(".txt") trap.