Python Foundations & The 6-Step Method · Lesson 3 of 5

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.

By Shahriyar · Updated

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

Parsing a log line? Split it. Building a report row? Join it.

Clean & search

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

▸ parse_log.py
# 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

All lessons in Python Foundations & The 6-Step Method

  1. Variables, Types, Control Flow & Functions
  2. Lists, Dicts, Sets & Tuples — When and Why
  3. String Manipulation Patterns
  4. The 6-Step Method — A Worked Example
  5. Hand-Tracing — Where Logic Actually Grows