Module 7: Strings in Depth -- Study Guide
Review all key concepts from Module 7. Use this guide to prepare for the quiz or as a reference while coding.
1. Strings Are Immutable
Core Principle: Strings cannot be changed in place. Every string method returns a NEW string -- the original is never modified. This is the fundamental difference from lists.
name = "alice" upper_name = name.upper() # Returns "ALICE" print(name) # Still "alice" # To keep the change, reassign: name = name.upper() # Now name is "ALICE"
Common mistake: Calling a string method without saving the result.
text.upper() alone does nothing to text. You must write text = text.upper() or result = text.upper().
2. String Methods
Case Conversion
.upper()-- all uppercase.lower()-- all lowercase.title()-- capitalize each word.capitalize()-- capitalize first letter only.swapcase()-- swap upper and lower
Whitespace Removal
.strip()-- remove whitespace from both ends.lstrip()-- remove from left only.rstrip()-- remove from right only- All three accept optional characters to strip:
.strip("#")
Other Key Methods
.replace(old, new)-- substitute all occurrences.count(sub)-- count occurrences of substring.startswith(sub)/.endswith(sub)-- check boundaries
Tip:
startswith() and endswith() accept tuples for multiple checks: filename.endswith((".jpg", ".png"))
3. String Slicing
Same as Lists: String slicing uses identical syntax to list slicing:
string[start:stop:step]
Key patterns:
s[:n]-- first n characterss[-n:]-- last n characterss[a:b]-- from index a to b-1s[::2]-- every other characters[::-1]-- reversed strings[1:-1]-- everything except first and last
text = "Programming" print(text[:4]) # "Prog" print(text[-4:]) # "ming" print(text[::-1]) # "gnimmargorP"
4. Searching Strings
find() vs index()
find(sub)-- returns index of first match, or -1 if not foundindex(sub)-- returns index of first match, or raises ValueError if not foundrfind(sub)-- like find(), but searches from the right (last occurrence)
When to use which: Use
find() when the substring might not exist (check for -1). Use index() when not finding it would be a bug.
The in Operator
if "python" in text.lower(): print("Found it!")
Always convert to the same case for case-insensitive searches.
5. Splitting and Joining
split() and join() are inverses:
split() turns a string into a list; join() turns a list into a string.
# Split words = "Hello World".split() # ["Hello", "World"] parts = "a,b,c".split(",") # ["a", "b", "c"] # Join result = " ".join(["Hello", "World"]) # "Hello World" result = ",".join(["a", "b", "c"]) # "a,b,c" # Clean up spacing clean = " ".join(" too many spaces ".split()) # "too many spaces"
Remember:
join() is called on the separator, not the list: ",".join(my_list) not my_list.join(",").
6. Special String Types
- f-strings:
f"Hello {name}"-- embed expressions inside strings - Raw strings:
r"C:\path\file"-- backslashes are literal - Multiline:
"""triple quotes"""-- span multiple lines
Use splitlines() to split multiline strings into a list of lines.
7. Common Patterns
# Case-insensitive comparison if user_input.lower() == "yes": # Extract email parts at = email.find("@") username = email[:at] domain = email[at+1:] # Extract file extension ext = filename[filename.rfind(".")+1:] # Check palindrome is_palindrome = word.lower() == word.lower()[::-1] # Clean phone number clean = "".join(c for c in phone if c.isdigit()) # Parse CSV for line in csv_text.split("\n"): fields = line.split(",")
8. Strings vs. Lists -- Comparison
| Feature | Strings | Lists |
|---|---|---|
| Mutable? | No (immutable) | Yes (mutable) |
| Indexing | Yes | Yes |
| Slicing | Yes | Yes |
in operator | Yes | Yes |
len() | Yes | Yes |
| Methods modify in place? | No (return new string) | Yes (most return None) |
sort() / reverse() | Not available | Available |
9. Review Questions
Q1: Why do string methods return new strings instead of modifying the original?
Q2: What is the difference between find() and index()?
Q3: How do you reverse a string?
Q4: What does split() return, and what does join() do?
Q5: How do you perform a case-insensitive search?
Q6: What is a raw string and when would you use one?
Q7: How do you check if a filename ends with ".pdf" or ".txt"?
Q8: What is the most efficient way to build a string from many pieces?