- Case conversion β upper(), lower(), capitalize(), title()
- Checking methods β isalpha(), isdigit(), isalnum(), isspace()
- Searching methods β find(), index(), count(), startswith(), endswith()
- Modifying methods β replace(), strip(), split(), join()
- Alignment methods β center(), ljust(), rjust(), zfill()
- Real-world examples β practical applications
What Are String Methods?
String methods are functions that belong to string objects. They let you do all kinds of things with text β change its case, search for patterns, split it into pieces, clean it up, and much more. Think of them as a Swiss Army knife for working with text.
Unlike operators, which are symbols like + and *, methods are called using dot notation. For example, instead of upper(text), you write text.upper(). This is because methods are attached to the string itself.
Here's the thing about string methods β they're immutable. That means they don't change the original string. Instead, they return a new string with the changes applied. This is a good thing because it makes your code more predictable and easier to debug.
π‘ Key concept: String methods are functions that belong to strings. They don't change the original string β they return a new one. This makes them safe and predictable to use.
Case Conversion Methods
Changing Letter Cases
# Python provides several methods to change the case of strings
text = "hello world"
# 1. upper() - convert to uppercase
print(text.upper()) # HELLO WORLD
# 2. lower() - convert to lowercase
text2 = "HELLO WORLD"
print(text2.lower()) # hello world
# 3. capitalize() - first letter uppercase, rest lowercase
text = "hello world"
print(text.capitalize()) # Hello world
# 4. title() - first letter of each word uppercase
text = "hello world"
print(text.title()) # Hello World
# 5. swapcase() - swap uppercase and lowercase
text = "Hello World"
print(text.swapcase()) # hELLO wORLD
# 6. casefold() - aggressive lowercasing (for case-insensitive comparisons)
text = "StraΓe" # German
print(text.casefold()) # strasse
# 7. Practical: Converting user input to lowercase for comparison
user_input = "Yes"
if user_input.lower() == "yes":
print("User said yes")
Case methods summary:
- upper() β all characters to uppercase
- lower() β all characters to lowercase
- capitalize() β first letter uppercase
- title() β first letter of each word uppercase
- swapcase() β swaps case of each character
- casefold() β aggressive lowercasing for comparison
Quick Check: Which method converts the first letter of each word to uppercase? (Answer: title())
Checking Methods (isalpha, isdigit, etc.)
Checking What's Inside a String
# Checking methods return True or False
# 1. isalpha() - all characters are letters
print("Hello".isalpha()) # True
print("Hello123".isalpha()) # False
print("".isalpha()) # False
# 2. isdigit() - all characters are digits
print("123".isdigit()) # True
print("123a".isdigit()) # False
print("".isdigit()) # False
# 3. isalnum() - all characters are letters or digits
print("Hello123".isalnum()) # True
print("Hello 123".isalnum()) # False (space)
print("".isalnum()) # False
# 4. isspace() - all characters are whitespace
print(" ".isspace()) # True
print(" a ".isspace()) # False
print("".isspace()) # False
# 5. isupper() - all characters are uppercase
print("HELLO".isupper()) # True
print("Hello".isupper()) # False
# 6. islower() - all characters are lowercase
print("hello".islower()) # True
print("Hello".islower()) # False
# 7. istitle() - string is titlecased (each word starts with uppercase)
print("Hello World".istitle()) # True
print("Hello world".istitle()) # False
# 8. Practical: Validating user input
username = input("Enter username (letters only): ")
if username.isalpha():
print("Valid username")
else:
print("Username can only contain letters")
Checking methods summary:
- isalpha() β letters only
- isdigit() β digits only
- isalnum() β letters or digits
- isspace() β whitespace only
- isupper() β all uppercase
- islower() β all lowercase
- istitle() β title case
Quick Check: Which method checks if a string contains only digits? (Answer: isdigit())
Searching Methods (find, index, count)
Finding Things in Strings
# Searching methods help you find substrings
text = "Python is amazing. Python is powerful."
# 1. find() - returns first index or -1 if not found
print(text.find("Python")) # 0
print(text.find("Java")) # -1
print(text.find("is")) # 7
# 2. find() with start and end
print(text.find("Python", 10)) # 21 (search from index 10)
# 3. rfind() - returns last index or -1 if not found
print(text.rfind("Python")) # 21
# 4. index() - like find(), but raises ValueError if not found
print(text.index("Python")) # 0
# print(text.index("Java")) # ValueError
# 5. count() - count occurrences
print(text.count("Python")) # 2
print(text.count("is")) # 2
# 6. startswith() - check if string starts with a prefix
print(text.startswith("Python")) # True
print(text.startswith("Java")) # False
# 7. endswith() - check if string ends with a suffix
text2 = "hello.txt"
print(text2.endswith(".txt")) # True
print(text2.endswith(".pdf")) # False
# 8. Practical: Finding file extensions
filename = "document.pdf"
if filename.endswith(".pdf"):
print("This is a PDF file")
# 9. Practical: Extracting username from email
email = "user@example.com"
at_index = email.find("@")
username = email[:at_index]
print(f"Username: {username}")
Searching methods summary:
- find() β returns index or -1
- index() β returns index or raises error
- rfind() β finds from the right
- count() β counts occurrences
- startswith() β checks prefix
- endswith() β checks suffix
Quick Check: What's the difference between find() and index()? (Answer: find() returns -1 if not found, index() raises ValueError)
Modifying Methods (replace, strip, split, join)
Changing and Cleaning Strings
# These methods modify strings in various ways
# 1. replace() - replace occurrences of a substring
text = "Hello World"
print(text.replace("World", "Python")) # Hello Python
print(text.replace("l", "L")) # HeLLo WorLd
# replace() with count
text = "aaa bbb aaa"
print(text.replace("a", "x", 2)) # xxa bbb aaa (only first 2)
# 2. strip() - remove whitespace from both ends
text = " Hello "
print(text.strip()) # "Hello"
print(text.lstrip()) # "Hello " (only left)
print(text.rstrip()) # " Hello" (only right)
# 3. strip() with custom characters
text = "!!!Hello!!!"
print(text.strip("!")) # Hello
# 4. split() - split string into a list
text = "apple,banana,cherry"
print(text.split(",")) # ['apple', 'banana', 'cherry']
print(text.split()) # ['apple,banana,cherry']
# 5. split() with max splits
text = "one,two,three,four"
print(text.split(",", 2)) # ['one', 'two', 'three,four']
# 6. join() - join a list into a string
words = ["apple", "banana", "cherry"]
print(", ".join(words)) # apple, banana, cherry
# 7. Practical: Cleaning user input
user_input = " Hello "
cleaned = user_input.strip()
print(f"'{cleaned}'") # 'Hello'
# 8. Practical: Parsing CSV data
csv_line = "Alice,25,Engineer"
parts = csv_line.split(",")
print(f"Name: {parts[0]}, Age: {parts[1]}, Job: {parts[2]}")
Modifying methods summary:
- replace() β replaces substrings
- strip() β removes whitespace from ends
- lstrip() β removes from left only
- rstrip() β removes from right only
- split() β splits into a list
- join() β joins a list into a string
Quick Check: What method removes whitespace from both ends of a string? (Answer: strip())
Alignment Methods (center, ljust, rjust)
Positioning Text
# These methods help you align text
# 1. center() - center align with padding
text = "Hello"
print(text.center(10)) # " Hello "
print(text.center(10, "*")) # "**Hello***"
# 2. ljust() - left align with padding
text = "Hello"
print(text.ljust(10)) # "Hello "
print(text.ljust(10, "-")) # "Hello-----"
# 3. rjust() - right align with padding
text = "Hello"
print(text.rjust(10)) # " Hello"
print(text.rjust(10, "-")) # "-----Hello"
# 4. zfill() - pad with zeros on the left
number = "42"
print(number.zfill(5)) # "00042"
# 5. Practical: Creating a table
def create_table_row(text, width=20):
return "| " + text.ljust(width - 2) + " |"
print(create_table_row("Name"))
print(create_table_row("Age"))
print(create_table_row("City"))
# 6. Practical: Progress display
def format_progress(percent):
return f"[{str(percent).rjust(3)}%]"
print(format_progress(5)) # "[ 5%]"
print(format_progress(100)) # "[100%]"
# 7. Creating a nice header
header = "WELCOME"
print(header.center(40, "="))
# "===============WELCOME================"
Alignment methods summary:
- center() β center aligns the string
- ljust() β left aligns the string
- rjust() β right aligns the string
- zfill() β pads with zeros
Quick Check: Which method would you use to pad a number with zeros? (Answer: zfill())
Try It Yourself
Experiment with string methods in the editor below.
STRING METHODS PRACTICE
========================================
1. CASE CONVERSION
Upper: ' HELLO WORLD '
Lower: ' hello world '
Title: ' Hello World '
Capitalize: ' hello world '
2. CHECKING METHODS
Is alpha: True
Is digit: True
Is alnum: True
3. SEARCHING METHODS
Find 'Python': 0
Count 'Python': 2
Starts with 'Python': True
4. MODIFYING METHODS
Strip: 'hello world'
Replace: ' hi world '
Split: ['hello', 'world']
5. ALIGNMENT METHODS
Center: '** hello world **'
Left: ' hello world '
Right: ' hello world '
String methods practice complete!
You've Got It!
You now know Python's most important string methods. From case conversion to searching, cleaning, and alignment β you have the tools to work with text effectively.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between upper() and capitalize()?
What is the difference between strip() and replace()?
What's a common interview question about string methods?
Do string methods change the original string?
text = text.upper() β you're assigning the new string back to the variable.
When should I use isdigit() vs isnumeric()?
How do I join a list of strings?
join() method on the separator string: ", ".join(["apple", "banana", "cherry"]) gives "apple, banana, cherry". The separator is the string you call join() on.
Where to Go From Here
Now that you've mastered string methods, check out these related topics:
π Assignments
Practice what you've learned with assignments.
Learn More βRegular Expressions
Learn advanced pattern matching with regex.
Learn More βObject-Oriented Programming
Learn about classes and objects in Python.
Learn More β