Lesson 4 of 41
Conditional Logic, Branching & Truthy/Falsy Evaluation
Overview & Learning Objectives
Text data in analytics workflows arrives messy: inconsistent casing, whitespace padding, delimiter concatenations, and unformatted currencies. Python strings are immutable sequences of Unicode characters that provide powerful built-in sequence slicing `[start:stop:step]` and vectorized manipulation methods to sanitize dirty operational records.
- Extract text substrings using start, stop, and step slice indexing.
- Clean messy customer text entries using `strip()`, `split()`, `join()`, and `replace()`.
- Format executive business summary strings using modern Python f-strings with numeric and currency specifiers.
Industry Standard
Standard: Analytics pipelines at Uber and Airbnb require stripping leading/trailing whitespace and lowercasing email strings at data ingestion boundaries to prevent duplicate user profile records.
Real-World Example: ScoopCraft Customer Receipt Formatter
ScoopCraft parses dirty online customer order codes and formats customer receipt SMS messages.
| Raw String Code | Cleaning Operation | Sanitized Result |
|---|---|---|
| #ORD-2026-DELHI-0042 | strip() & upper() | ORD-2026-DELHI-0042 |
| Rider: Ramesh Kumar (+919876543210) | split(":") & slice | Ramesh Kumar |
| ICE-CREAM,BELGIAN,TUB,500ML | split(",") & join(" > ") | ICE-CREAM > BELGIAN > TUB > 500ML |
| Gross: 14250.75 | f"{amount:,.2f}" | ₹14,250.75 |
Syntax & Core Code Implementation
# String slicing: [start:stop:step]
sku_code = "SKU-ZEPTO-MUM-8901"
prefix = sku_code[:3] # "SKU"
store_hub = sku_code[10:13] # "MUM"
reversed_sku = sku_code[::-1]
# Cleaning and tokenizing
dirty_input = " vanilla crunch tub \n"
clean_text = dirty_input.strip().title() # "Vanilla Crunch Tub"
parts = "BLR,BOM,DEL,HYD".split(",") # ["BLR", "BOM", "DEL", "HYD"]
rejoined = " | ".join(parts) # "BLR | BOM | DEL | HYD"
# Modern f-string formatting
sales = 1450200.8
growth = 0.1875
report = f"Gross Sales: ₹{sales:,.2f} | YoY Growth: {growth:.1%}"
Parameters & Arguments Breakdown
strip([chars]): Removes leading and trailing characters (defaults to whitespace and newlines).split(sep): Splits string on specified delimiter and returns a list of substring tokens.join(iterable): Concatenates elements of an iterable into a single string using caller string as delimiter.f"{val:,.2f}": F-string format specifier inserting comma thousands separator and 2 decimal places.
Sample Walkthrough (Q&A)
Question: How do you extract the file extension from a string like `"monthly_sales_march_2026.xlsx"` reliably?
Code Pattern: filename.rsplit(".", 1)[-1]
Result: "xlsx"
Explanation: `rsplit(".", 1)` splits from the right on the last dot only, correctly extracting "xlsx" even if filename has other dots.
Common Mistakes & Limitations
- Assuming `string.replace()` modifies the string in-place; since strings are immutable, the return value must be assigned to a variable.
- Using slow string concatenation `+` in large loops instead of accumulating strings in a list and calling `"".join(list)`.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Quick F-string evaluation | f"{val=}" | f"{val=}" |
| Multiline Raw String | r"""raw""" | r"""raw""" |
Pro Tips & Modern Best Practices
- Use `str.removeprefix("prefix")` and `str.removesuffix("suffix")` (Python 3.9+) instead of fragile slice indexing.
- Use Python 3.12+ enhanced f-strings allowing quotes, multiline expressions, and backslashes directly within `{}`.