String Methods
Python strings come with powerful built-in methods — functions attached to string objects that let you search, modify, check, and transform text without writing complex loops.
Learning Objectives
- 11.2.2.3 Apply string methods
Conceptual Anchor
The Swiss Army Knife
String methods are like a Swiss Army knife for text. Each blade (method) serves a specific purpose: one for converting case, another for searching, another for trimming spaces. Since strings are immutable, every method returns a new string — the original stays unchanged.
Rules & Theory
Case Methods
| Method | Description | Example | Result |
|---|---|---|---|
.upper() |
All uppercase | "hello".upper() |
"HELLO" |
.lower() |
All lowercase | "HELLO".lower() |
"hello" |
.title() |
Title Case | "hello world".title() |
"Hello World" |
.capitalize() |
First char upper | "hello world".capitalize() |
"Hello world" |
.swapcase() |
Switch case | "Hello".swapcase() |
"hELLO" |
Search & Replace Methods
| Method | Description | Example | Result |
|---|---|---|---|
.find(sub) |
Index of first occurrence (-1 if not found) | "hello".find("ll") |
2 |
.index(sub) |
Like find() but raises ValueError | "hello".index("ll") |
2 |
.count(sub) |
Count occurrences | "banana".count("a") |
3 |
.replace(old, new) |
Replace all occurrences | "hello".replace("l", "r") |
"herro" |
.startswith(s) |
Starts with prefix? | "hello".startswith("he") |
True |
.endswith(s) |
Ends with suffix? | "hello.py".endswith(".py") |
True |
Whitespace & Checking Methods
| Method | Description | Example | Result |
|---|---|---|---|
.strip() |
Remove leading/trailing whitespace | " hi ".strip() |
"hi" |
.lstrip() |
Remove leading whitespace | " hi ".lstrip() |
"hi " |
.rstrip() |
Remove trailing whitespace | " hi ".rstrip() |
" hi" |
.isdigit() |
All characters are digits? | "123".isdigit() |
True |
.isalpha() |
All characters are letters? | "abc".isalpha() |
True |
.isalnum() |
All alphanumeric? | "abc123".isalnum() |
True |
.isupper() |
All uppercase? | "ABC".isupper() |
True |
.islower() |
All lowercase? | "abc".islower() |
True |
Methods Return NEW Strings!
s.upper() does NOT change s. You must assign the result:
s = s.upper(). This is because strings are immutable.
Worked Examples
1 Input Validation
# Clean and validate user input
name = input("Enter your name: ").strip().title()
age = input("Enter your age: ").strip()
if not age.isdigit():
print("Error: age must be a number!")
else:
print(f"Hello, {name}! You are {age} years old.")2 Word Counter
sentence = input("Enter a sentence: ")
word = input("Search for word: ").lower()
# Case-insensitive count
count = sentence.lower().count(word)
print(f"'{word}' appears {count} time(s)")
# Find the position
pos = sentence.lower().find(word)
if pos != -1:
print(f"First occurrence at index {pos}")
else:
print("Word not found")3 Censoring Words
text = "Python is awesome and Python is fun"
censored = text.replace("Python", "***")
print(censored)
# "*** is awesome and *** is fun"
# Replace only first occurrence
censored2 = text.replace("Python", "***", 1)
print(censored2)
# "*** is awesome and Python is fun"4 File Extension Checker
filename = input("Enter filename: ")
if filename.endswith(".py"):
print("Python file")
elif filename.endswith((".jpg", ".png", ".gif")):
print("Image file")
elif filename.endswith(".txt"):
print("Text file")
else:
print("Unknown file type")Pitfalls & Common Errors
Forgetting to Assign the Result
name.upper() alone doesn't change name. You must write
name = name.upper().
find() vs index()
find() returns -1 if not found. index() raises
ValueError if not found. Use find() when the substring might be
absent.
Case Sensitivity
"Hello".find("hello") returns -1 because searches are case-sensitive.
Convert both to lowercase first for case-insensitive search.
Pro-Tips for Exams
Method Chaining
- You can chain methods:
" Hello ".strip().lower()→"hello" find()returns -1 (not False), so always compare with!= -1replace()replaces ALL occurrences by default. Add 3rd argument to limit.isdigit()returns False for empty strings and negative numbers- Always clean input with
.strip()— users often add accidental spaces
Graded Tasks
Name 5 string methods and describe what each does.
Explain the difference between find() and index().
Write a program that counts the number of vowels, consonants, digits, and spaces in a user-input string.
Write a program that validates a username: must be 3-15 characters, alphanumeric only, no spaces.
What is the output of:
s = " Hello World "; print(s.strip().replace("World", "Python").lower())?
Build a simple text encryptor: shift each letter by 1 position (a→b, z→a). Use
ord() and chr().
Self-Check Quiz
" hello ".strip() return?"banana".count("an") return?"hello".upper() change the original string?"hello".find("xyz") return?"123abc".isdigit() return?