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!