Python String Methods and Formatting Practice
Python built-in string methods like `.split()`, `.join()`, and `.replace()` are essential tools for parsing CSV lines, cleaning user inputs, and restructuring strings. Tracing how `.split()` handles consecutive delimiters (`no arg vs explicit arg`) ensures accurate parsing.
Core Conceptual Insights
Theoretical Blueprint:`.split()` takes a beaded necklace and cuts the string at every knot (`delimiter`), leaving separate beads (`list of strings`). `.join()` takes those separate beads and threads them onto a new string using a chosen spacer pattern.
Common Developer Trap:Many developers don't know that `.split()` with NO arguments strips and groups all consecutive whitespace (`['a', 'b']`), whereas `.split(' ')` with an explicit single space preserves empty strings for every consecutive space (`['a', '', 'b']`).
Structured Practice Breakdown
`.split()` with no arguments vs explicit space
text = 'a b'
print(len(text.split()), len(text.split(' ')))2 4Execution Walkthrough
`text.split() -> ['a', 'b']` (`len 2`). `text.split(' ') -> ['a', '', '', 'b']` (`len 4`). Output: `2 4`.
`.join()` across a list of strings
parts = ['2026', '07', '17']
print('-'.join(parts))2026-07-17Execution Walkthrough
Calling `'-'.join(['2026', '07', '17'])` joins the three string elements using hyphen separators, producing `'2026-07-17'`.
`.find()` vs `.index()` on missing substring
s = 'python'
print(s.find('z'))
try:
s.index('z')
except ValueError:
print('index raised ValueError')-1
index raised ValueErrorExecution Walkthrough
`s.find('z')` returns `-1`. Then `s.index('z')` raises `ValueError: substring not found`, which is caught and printed.
`.replace()` with maximum count limit
text = 'apple apple apple'
print(text.replace('apple', 'orange', 2))orange orange appleExecution Walkthrough
Calling `.replace('apple', 'orange', 2)` replaces only the first two instances, leaving `'orange orange apple'`.