String Manipulation Patterns
Testers live in text — log lines, CSV rows, URLs, JSON snippets. A small handful of string patterns handle almost all of it, and none of them are hard.
The idea, in one line
You mostly do four things to text: grab a piece of it, break it apart, clean it up, and build a new string from the pieces.
Index & slice — grab a piece
s[0] is the first character, s[-1] the last. A slice s[start:end] keeps start and stops just before end, so "Python"[0:2] is "Py". Slicing never crashes on out-of-range numbers — it just gives you what it can.
Split & join — the workhorse pair
text.split(",")turns"a,b,c"into["a", "b", "c"]",".join(parts)stitches a list back into"a,b,c"
Parsing a log line? Split it. Building a report row? Join it.
Clean & search
strip()trims spaces and newlines off the endslower()/upper()fix the case so"PASS"and"pass"count as equalreplace(old, new)swaps one bit of text for another"ERROR" in linechecks whether a word appears inside the text
Build results with f-strings
An f-string like f"{name}: {status}" drops values straight into text — just put an f in front of the quotes and your names in { }. When you're gluing lots of pieces together, collect them in a list and join once at the end.
See it work
# Turn a raw log line into fields, then rebuild a clean summary
line = " 2024-05-01,ERROR,login timed out "
parts = line.strip().split(",") # ['2024-05-01', 'ERROR', 'login timed out']
date, level, message = parts # unpack into three names
# Fix the case, then test it
if level.lower() == "error":
print(f"[{date}] {message.upper()}")
# 'in' checks for a word; replace swaps text
if "timed out" in message:
print(message.replace("timed out", "TIMEOUT"))
# Build one report row from many fields
print(" | ".join([date, level, "login"]))Read it top to bottom: you trimmed the line, split it into fields, checked and reshaped the text, then joined pieces back into a tidy row. That's the whole loop of working with text.
Advanced — why join beats gluing with +
Because strings can't change in place, every + in a loop builds a brand-new string and throws the old one away. Do that a thousand times and it adds up. "".join(list_of_pieces) builds the result in one go instead — cleaner to read and quicker when there are lots of pieces. Reach for join whenever you're assembling text in a loop.
Grounded in the official Python tutorial & common string-method references