Lesson 7.1: String Methods
By the end of this lesson, you will be able to:
- Change the case of strings using upper(), lower(), and title()
- Remove whitespace using strip(), lstrip(), and rstrip()
- Replace parts of strings using replace()
- Count occurrences with count()
- Check string beginnings and endings with startswith() and endswith()
Strings Are Immutable
name = "alice" result = name.upper() print(result) # New string print(name) # Original unchanged
To keep the result, you must assign it to a variable (either the same variable or a new one).
name = "alice" name = name.upper() # Reassign to same variable print(name)
Case Conversion Methods
upper() and lower()
message = "Hello, World!" print(message.upper()) # All uppercase print(message.lower()) # All lowercase
title() and capitalize()
text = "the quick brown fox" print(text.title()) # Capitalize Each Word print(text.capitalize()) # Capitalize first letter only
Practical Use: Case-Insensitive Comparison
user_input = "YES" # Compare in lowercase so "YES", "Yes", "yes" all work if user_input.lower() == "yes": print("User confirmed!")
swapcase()
text = "Hello World" print(text.swapcase())
Stripping Whitespace
The strip() family of methods removes leading and/or trailing whitespace (spaces, tabs, newlines).
messy = " Hello, World! " print(f"'{messy.strip()}'") # Both sides print(f"'{messy.lstrip()}'") # Left side only print(f"'{messy.rstrip()}'") # Right side only
Stripping Specific Characters
You can also strip specific characters by passing them as an argument.
data = "###Price: $25.99###" print(data.strip("#")) url = "https://example.com/" print(url.rstrip("/"))
Try It Yourself
Take the string " Welcome to Python! ". Strip it, convert it to uppercase, and print the result.
The replace() Method
replace(old, new) returns a new string with all occurrences of old replaced by new.
sentence = "I like cats. Cats are great." print(sentence.replace("cats", "dogs"))
Note that replace() is case-sensitive. "Cats" was not replaced because it starts with a capital C.
Limiting Replacements
You can limit how many replacements are made with a third argument.
text = "one fish, two fish, red fish, blue fish" print(text.replace("fish", "bird", 2)) # Replace only first 2
Chaining replace() Calls
# Clean up a phone number phone = "(555) 123-4567" clean = phone.replace("(", "").replace(")", "").replace("-", "").replace(" ", "") print(clean)
The count() Method
count() returns the number of non-overlapping occurrences of a substring.
text = "banana" print(text.count("a")) print(text.count("an")) print(text.count("z"))
Counting Words in a Sentence
paragraph = "Python is great. Python is popular. Python is fun." print(f"'Python' appears {paragraph.count('Python')} times") print(f"Sentences: {paragraph.count('.')}")
startswith() and endswith()
These methods return True or False based on whether a string starts or ends with a given substring.
filename = "report_2024.pdf" print(filename.startswith("report")) print(filename.endswith(".pdf")) print(filename.endswith(".txt"))
Practical Use: File Type Checking
files = ["photo.jpg", "report.pdf", "data.csv", "image.png", "notes.txt"] images = [f for f in files if f.endswith((".jpg", ".png"))] print("Image files:", images)
You can pass a tuple of strings to check multiple endings at once!
Checking Methods: isdigit(), isalpha(), isalnum()
print("123".isdigit()) # All digits? print("hello".isalpha()) # All letters? print("abc123".isalnum()) # All letters or digits? print("hello".islower()) # All lowercase? print("HELLO".isupper()) # All uppercase?
Check Your Understanding
- What does
"hello world".title()return? - What does
" python ".strip()return? - Does
replace()modify the original string? - What does
"banana".count("na")return?
"Hello World""python"- No. Strings are immutable.
replace()returns a new string. 2
Key Takeaways
- Strings are immutable -- all methods return a new string, never modify the original
upper(),lower(),title()change case; useful for comparisonsstrip(),lstrip(),rstrip()remove whitespace (or specified characters)replace(old, new)substitutes all occurrences; optionally limit with a countcount()returns how many times a substring appearsstartswith()andendswith()check string boundaries; accept tuples for multiple checks