Chapter 13: String Methods¶
🚀 Open Notebook¶
📺 Video Tutorial¶
String methods in Python are easy! 〰️ (12:14)
📚 What You’ll Learn¶
Master Python’s powerful string manipulation methods to transform and analyze text!
🎯 Learning Objectives¶
Use common string methods (.upper(), .lower(), .title(), etc.)
Find and replace substrings
Validate string content
Combine multiple string operations
📖 Concept Explanation¶
Strings in Python come with many built-in methods for manipulation. Methods are functions that belong to an object (in this case, strings).
Common String Methods¶
Method |
Description |
Example |
|---|---|---|
|
Convert to uppercase |
|
|
Convert to lowercase |
|
|
Capitalize first letter of each word |
|
|
Capitalize first letter only |
|
|
Find substring index |
|
|
Replace substring |
|
|
Check if all digits |
|
|
Check if all letters |
|
|
Remove whitespace |
|
|
Split into list |
|
💡 Examples¶
Example 1: Case Conversion¶
name = "john DOE"
print(name.upper()) # JOHN DOE
print(name.lower()) # john doe
print(name.title()) # John Doe
print(name.capitalize()) # John doe
Example 2: Finding Substrings¶
text = "Python Programming"
print(text.find("Pro")) # 7 (index where "Pro" starts)
print(text.find("Java")) # -1 (not found)
print("Pro" in text) # True (membership check)
Example 3: Replacing Text¶
phone = "123-456-7890"
clean = phone.replace("-", "")
print(clean) # 1234567890
message = "Hello World"
new_msg = message.replace("World", "Python")
print(new_msg) # Hello Python
Example 4: Validation¶
user_input = "12345"
if user_input.isdigit():
number = int(user_input)
print(f"Valid number: {number}")
else:
print("Please enter only digits")
✍️ Practice Exercises¶
Create a program that converts usernames to lowercase
Clean phone numbers by removing spaces and dashes
Validate email format (contains @ and .)
Count how many times a letter appears in a word
Create a function that capitalizes names properly
Build a simple text processor that removes extra spaces
📝 More Useful Methods¶
.count(substring)¶
text = "hello world"
print(text.count("l")) # 3
.startswith() and .endswith()¶
filename = "document.pdf"
print(filename.endswith(".pdf")) # True
print(filename.startswith("doc")) # True
.strip(), .lstrip(), .rstrip()¶
text = " hello "
print(text.strip()) # "hello" (both sides)
print(text.lstrip()) # "hello " (left side)
print(text.rstrip()) # " hello" (right side)
.split() and .join()¶
# Split string into list
sentence = "Python is awesome"
words = sentence.split() # ['Python', 'is', 'awesome']
# Join list into string
joined = " ".join(words) # "Python is awesome"
csv = ",".join(words) # "Python,is,awesome"
🎮 Real-World Examples¶
Email Validator¶
email = input("Enter email: ")
if "@" in email and "." in email:
domain = email.split("@")[1]
print(f"Domain: {domain}")
else:
print("Invalid email format")
Username Formatter¶
username = input("Username: ")
username = username.strip().lower().replace(" ", "_")
print(f"Formatted username: {username}")
Password Strength Checker¶
password = input("Enter password: ")
has_digit = any(c.isdigit() for c in password)
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
if len(password) >= 8 and has_digit and has_upper and has_lower:
print("Strong password!")
else:
print("Weak password")
🚀 Challenge Projects¶
Text Analyzer: Count words, letters, vowels, consonants
Name Formatter: Handle various name formats (JOHN DOE, john doe, etc.)
Censorship Filter: Replace bad words with asterisks
Acronym Generator: Create acronyms from phrases (e.g., “For Your Information” → “FYI”)
Text Reverser: Reverse words and sentences in different ways
🎓 Key Takeaways from Video¶
Strings are text data enclosed in quotes
Define functions using the def keyword
Use if-elif-else for conditional logic
💡 These points cover the main concepts from the video tutorial to help reinforce your learning.
🔗 Next Chapter¶
Continue to Chapter 14: Indexing to learn how to access individual characters!