Learn Without Walls
← Module 7 Home Lesson 1 of 4 Lesson 2 →

Lesson 7.1: String Methods

By the end of this lesson, you will be able to:

Strings Are Immutable

Immutable: Strings cannot be changed in place. Every string method returns a new string -- the original remains unchanged. This is the key difference from lists!
name = "alice"
result = name.upper()

print(result)    # New string
print(name)      # Original unchanged
ALICE alice

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)
ALICE

Case Conversion Methods

upper() and lower()

message = "Hello, World!"

print(message.upper())   # All uppercase
print(message.lower())   # All lowercase
HELLO, WORLD! hello, world!

title() and capitalize()

text = "the quick brown fox"

print(text.title())       # Capitalize Each Word
print(text.capitalize())   # Capitalize first letter only
The Quick Brown Fox The quick brown fox

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!")
User confirmed!

swapcase()

text = "Hello World"
print(text.swapcase())
hELLO wORLD

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
'Hello, World!' 'Hello, World! ' ' Hello, World!'

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("/"))
Price: $25.99 https://example.com

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"))
I like dogs. Cats are great.

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
one bird, two bird, red fish, blue fish

Chaining replace() Calls

# Clean up a phone number
phone = "(555) 123-4567"
clean = phone.replace("(", "").replace(")", "").replace("-", "").replace(" ", "")
print(clean)
5551234567

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"))
3 2 0

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('.')}")
'Python' appears 3 times Sentences: 3

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"))
True True False

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)
Image files: ['photo.jpg', 'image.png']

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?
True True True True True

Check Your Understanding

  1. What does "hello world".title() return?
  2. What does " python ".strip() return?
  3. Does replace() modify the original string?
  4. What does "banana".count("na") return?
  1. "Hello World"
  2. "python"
  3. No. Strings are immutable. replace() returns a new string.
  4. 2

Key Takeaways