String Methods
Python’s most underrated superpower
📖 Concept Recap
Strings are immutable sequences — methods return new strings, they never modify in place.
- Cleaning:
.strip(),.lstrip(),.rstrip(),.lower(),.upper(),.title() - Searching:
.find(),.count(),.startswith(),.endswith(),in - Transforming:
.replace(old, new),.split(sep),sep.join(list) - Slicing:
s[start:stop:step]—s[::-1]reverses a string - f-strings:
f"Name: {name!r}, Score: {score:.2f}"
👀 Worked Example
Real-world string cleaning — standardizing messy name data:
Exercise 1 — Text Analyzer
Complete the text analyzer by filling in the blanks. Each blank uses a string method or variable you already have.
.split() (no arguments) to split on any whitespace. Use the in keyword to check if "Python" appears in text.Exercise 2 — Phone Number Formatter
Write a function format_phone(raw) that takes messy phone numbers and returns them all in the format 213-555-0123. Test all 4 formats:
'(213) 555-0123''2135550123''213.555.0123''+1-213-555-0123'
digits = ''.join(c for c in raw if c.isdigit()). Then take the last 10 digits and slice them into 3 parts: digits[-10:-7] + '-' + digits[-7:-4] + '-' + digits[-4:]Exercise 3 — Caesar Cipher
Write two functions:
encrypt(text, shift)— shifts each letter forward byshiftpositions in the alphabet (wraps around). Non-letters stay unchanged. Preserve case.decrypt(text, shift)— reverses the encryption
Test: Encrypt 'Hello World' with shift=3, then decrypt it back to verify.
Mini Project — Complete Text Analyzer
Build a full text analyzer. Given the paragraph below, calculate and print all 7 metrics:
- Total character count (with spaces) and without spaces
- Word count
- Sentence count
- Average word length (in characters)
- The 5 most frequent words (excluding stop words: the, a, an, is, are, and, of, to, that, from, in)
- Percentage of words that are unique
- The longest word in the text
word.strip('.,!?;:') before counting. For the top 5, sort the frequency dict by value: sorted(freq.items(), key=lambda x: x[1], reverse=True)[:5].✅ Lab 6 Complete!
You’ve mastered string cleaning, splitting, joining, slicing, and built a Caesar cipher and full text analyzer. String skills are essential for working with any real-world data.
Continue to Lab 7: Working with Data →