2.2 Strings, Indexing, Slicing & Essential Methods
Master Python text processing visually: positive and negative indexing, the [start:stop:step] slicing ruler, why strings are immutable, and the 10 string methods you will use every day.
1. What Is a String? (The Letter-Tile Analogy)
Think of a Python string (str) as a row of Scrabble letter tiles glued side-by-side inside a glass case. You can create strings with single quotes ('hi'), double quotes ("hi"), or triple quotes ("""multi-line"""):
single = 'Hello'
double = "It's a sunny day!" # Use double quotes when text has an apostrophe
multi = """Line 1
Line 2"""
raw = r"C:\Users\new_folder" # Raw string: ignores \n escape sequences!
2. Indexing & Slicing Ruler ([start:stop:step])
Every character in a string has two addresses:
- Positive index: starts at
0from the left (0, 1, 2, ...). - Negative index: starts at
-1from the right (-1is always the last character!).
The Universal Slicing Formula: s[start : stop : step]
startis included (defaults to0).stopis excluded — Python stops right beforestop!stepis the jump size (defaults to1;-1walks backward!).
s = "PYTHON"
print(s[0]) # "P" (first character)
print(s[-1]) # "N" (last character)
print(s[1:4]) # "YTH" (indices 1, 2, 3)
print(s[:3]) # "PYT" (first 3 characters)
print(s[3:]) # "HON" (from index 3 to end)
print(s[::2]) # "PTO" (every 2nd character)
print(s[::-1]) # "NOHTYP" (instant reverse!)
Memory Trick: Think of
s[1:4]as "length =4 - 1 = 3characters starting at index 1."
3. Immutability: Why word[0] = "b" Crashes
Remember our "Scrabble tiles locked in a glass case" analogy? Once a string is created in memory, you cannot modify a character inside it. Strings are immutable.
Every string method (.upper(), .strip(), .replace()) leaves the original string untouched and returns a brand-new string — so remember to save the return value!
name = " bigoslate "
name.strip() # ✗ Bug! Return value was thrown away — name still has spaces!
name = name.strip() # ✓ Saved! Now name == "bigoslate"
4. The 10 String Methods You Will Use Every Day
| Method | Example | Output | What It Does |
|---|---|---|---|
.strip() | " hi \n".strip() | "hi" | Removes leading/trailing spaces & newlines |
.lower() / .upper() | "Py".lower() | "py" | Converts case (great for case-insensitive compare) |
.replace(a, b) | "a-b".replace("-", "_") | "a_b" | Replaces all occurrences of a with b |
.split(sep) | "a,b,c".split(",") | ["a", "b", "c"] | Splits string into a list of words |
sep.join(list) | "-".join(["a", "b"]) | "a-b" | Joins a list of strings cleanly (fast O(N)) |
.startswith(p) | "app.py".endswith(".py") | True | Prefix / suffix check |
.find(sub) | "hello".find("lo") | 3 | Index of substring (-1 if not found) |
in operator | "py" in "python" | True | Cleanest membership check |
.isdigit() | "123".isdigit() | True | Checks if all characters are digits |
len(s) | len("python") | 6 | Built-in function returning character count |
5. Interactive Trace: Cleaning & Parsing Messy User Input
Watch how real-world Python code chains .strip(), .lower(), and .split() to clean a messy email/name input:
Quick Quiz: Module 2.2 — Strings & Slicing
s = "hello" s.upper() print(s)
Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Paste LeetCode-style level-order tree arrays, graph edge lists, or 2D matrices to render clean vector SVG diagrams and DFS traversals.