1. First Steps & Data Basics
Strings Deep Dive: Slicing, Formatting & Cleaning Text
Work confidently with text in Python: index and slice characters, understand why strings cannot be mutated in place, clean messy user input, and validate text with built-in methods.
- Pick individual characters and slices from strings using positive and negative indexes
- Understand why strings are locked (immutable) and why methods return new copies
- Clean and validate user text with .strip(), .lower(), .replace(), and .isdigit()
Almost everything users type into an app—names, search bars, email addresses, passwords, and file paths—arrives as text (strings). Knowing how to inspect, clean, and check strings cleanly saves hours of frustration.
Strings Are Sequences of Characters
Just like a train made of connected cars, a string is a sequence of individual characters. That means you can grab any character by its position (starting at 0!) or take a slice:
word = "Python"
print(word[0]) # 'P' (first character)
print(word[-1]) # 'n' (last character)
print(word[0:3]) # 'Pyt' (positions 0, 1, 2 — stops before 3)
print(len(word)) # 6 (total characters)Positive indexes count left-to-right (0..5), negative indexes count right-to-left (-6..-1). Slice [0:3] grabs "Pyt" and stops right before index 3.
Bonus Trick: Reversing a String ([::-1])
Adding a third number inside [start:stop:step] sets the step size. A step of -1 walks backward from end to start:
print("Python"[::-1]) # "nohtyP"Why Strings Are "Locked" (Immutable)
If you try to change a single letter directly, Python stops you with a TypeError:
name = "cat"
# name[0] = "b" <-- CRASH! TypeError: 'str' object does not support item assignmentWhy? Because in Python, strings are locked once created. Instead of editing an old string, string methods always give you back a brand-new string:
name = "cat"
new_name = "b" + name[1:] # Joins "b" + "at" -> "bat"
print(new_name) # "bat"
print(name) # Still "cat"Everyday String Methods
Notice how you must save the returned result into a variable (because the original string never changes by itself!):
| Method | What It Does | Example | Result |
|---|---|---|---|
.strip() | Removes spaces at start & end | " hi ".strip() | "hi" |
.lower() / .upper() | Converts letter casing | "Py".lower() | "py" |
.title() | Capitalizes each word | "alex smith".title() | "Alex Smith" |
.replace(a, b) | Swaps text a for b | "hi alex".replace("alex", "maya") | "hi maya" |
.split(sep) | Cuts string into a list | "a,b,c".split(",") | ["a", "b", "c"] |
.startswith(x) | Checks beginning (True/False) | "https://...".startswith("https") | True |
.isdigit() | Checks if every char is 0-9 | "42".isdigit() | True |
Writing email.strip().lower() on a line by itself throws away the cleaned copy! Always assign it:
email = email.strip().lower()
Predict, Run & Check
Before clicking Run Code, predict in your head what cleaned and is_valid will be!
Click “Run Code” to execute this snippet right in your browser.
Modify Challenge: Change raw_name to " 9alex! " and also check not cleaned[0].isdigit() inside is_valid so usernames starting with a digit are rejected (False).
Quick Checkpoints
Given text = ' Hello ', what does text.strip() followed by print(text) output?
Which expression checks whether code = '12345' contains only digits?