Every Python String Method Explained with Examples
Strings in Python come with a toolbox of built-in methods. These methods let you change case, remove extra spaces, search for words, split text apart, and much more.
Think of string methods like apps on your phone. Each one does one specific job. You don't need to memorize them all right now -- just know they exist so you can reach for the right one when you need it.
In this tutorial you'll learn every major string method with live examples you can run and modify. By the end, you'll be able to clean, search, split, and transform any text Python throws at you.
How to Convert Strings to Uppercase in Python
Python gives you five methods to change the case of a string. The two most common are upper() and lower().
upper() converts every letter to uppercase. lower() converts every letter to lowercase. These two are the workhorses you'll use most often.
title() capitalizes the first letter of every word -- like a book title. capitalize() only capitalizes the very first letter and lowercases everything else.
swapcase() flips every letter: uppercase becomes lowercase and vice versa. It's not common, but handy when you need it.
How to Remove Whitespace from Strings in Python
Extra spaces and invisible characters sneak into strings all the time -- from user input, file reading, or copy-pasting. Python's strip() family handles this perfectly.
strip() removes whitespace from both ends of a string. Think of it like trimming the crust off both sides of a sandwich.
lstrip() only trims the left side. rstrip() only trims the right side. The "l" and "r" stand for left and right.
We used repr() in the example so you can actually see the spaces. Normally, print() would hide the trailing spaces.
How to Search Inside a String in Python
Python gives you several ways to search for text inside a string. The most important ones are find(), count(), startswith(), and endswith().
How to Use find() and index() in Python
find() tells you where a substring first appears. It returns the index (position number) of the first match, starting from 0.
When find() can't locate the substring, it returns -1. This is its way of saying "not found."
index() does the same job as find(), but with one key difference: if the substring is not found, it raises a ValueError instead of returning -1.
text = "hello world"
result = text.find("xyz")
print(result) # -1 (safe, no crash)text = "hello world"
# result = text.index("xyz")
# ValueError: substring not found
# Use index() only when you're SURE
# the substring exists
result = text.index("world")
print(result) # 6How to Count Occurrences in a String with count()
count() tells you how many times a substring appears in the string. It's case-sensitive, so "The" and "the" are counted separately.
How to Check String Starts and Ends in Python
startswith() and endswith() return True or False. They're perfect for checking file extensions, URL prefixes, or any pattern at the edges of a string.
How to Replace Text in a Python String
replace() swaps every occurrence of one substring with another. It's like the find-and-replace feature in a word processor.
The third argument is optional. It limits how many replacements happen. Without it, replace() changes every match it finds.
Remember: replace() is case-sensitive. "cats" and "Cats" are treated as different substrings.
How to Split a String in Python
split() chops a string into a list of smaller strings. By default, it splits on any whitespace (spaces, tabs, newlines).
The first argument is the delimiter -- the character (or string) where the split happens. The second argument limits the number of splits.
rsplit() works the same way but splits from the right side. This matters when you use a limit.
How to Join a List into a String in Python
join() is the reverse of split(). It takes a list of strings and glues them together with a separator. The separator is the string you call join() on.
The syntax looks backward at first: separator.join(list). Think of it as: "use this separator to join that list."
A common pattern is splitting a string, modifying the pieces, and joining them back together.
How to Check String Content in Python
Python has a family of is____() methods that return True or False based on what a string contains. They're great for validating user input.
isalpha() checks for letters only. isdigit() checks for digits only. isalnum() checks for letters or digits (alphanumeric). isspace() checks for whitespace only.
These methods all return False on empty strings. An empty string has no characters to test, so nothing passes the check.
How to Pad and Align Strings in Python
Sometimes you need text to be a certain width -- for tables, receipts, or neat terminal output. Python's padding methods add characters to fill the gap.
center() centers the string within the given width. ljust() left-aligns and pads the right. rjust() right-aligns and pads the left.
zfill() is a shortcut for padding numbers with leading zeros. It's perfect for order numbers, timestamps, or file names like image_007.png.
How to Chain String Methods in Python
Since every string method returns a new string, you can call another method on the result. This is called method chaining.
Read chains from left to right: first strip, then lowercase, then replace. Each method works on the result of the previous one.
Practice Exercises
Time to put those string methods to work! Each exercise focuses on a different group of methods you just learned.
You have a messy string stored in the variable user_input. It has extra spaces on both sides and random uppercase letters.
Clean it up by:
1. Removing whitespace from both ends
2. Converting to all lowercase
Print the cleaned result. The output should be:
hello pythonCount how many times the word "the" appears in the sentence below. Use the count() method.
Print the result in this exact format:
the appears 4 timesHint: Convert to lowercase first so you catch both "the" and "The".
Replace every occurrence of "JavaScript" with "Python" in the sentence below and print the result.
Expected output:
I love Python. Python is great. Learning Python is fun.You have a line of comma-separated values. Split it into individual values and print each one on its own line.
Expected output:
Alice
25
New York
EngineerThis code tries to find the position of "Python" in a sentence. It works when the word exists, but crashes when it doesn't.
Fix the code so it:
"Word not found" when the word is missingExpected output:
Found at position 7
Word not foundHint: The bug is that index() crashes when the word is missing. Which method returns -1 instead of crashing?
Write a program that validates a username based on these rules:
Three usernames are provided. For each one, print "Valid" if it passes both rules, or "Invalid" if it fails either rule.
Expected output:
player42: Valid
ab: Invalid
hello world!: InvalidSummary: Python String Methods Cheat Sheet
| Here's a quick reference of every method covered in this tutorial: | ||
|---|---|---|
| --- | --- | --- |
upper() | All uppercase | "hi".upper() → "HI" |
lower() | All lowercase | "HI".lower() → "hi" |
title() | Capitalize each word | "hi there".title() → "Hi There" |
capitalize() | Capitalize first letter | "hi there".capitalize() → "Hi there" |
strip() | Remove edge whitespace | " hi ".strip() → "hi" |
find() | Position of substring (-1 if missing) | "hello".find("ll") → 2 |
count() | Count occurrences | "banana".count("a") → 3 |
startswith() | Check beginning | "hello".startswith("he") → True |
endswith() | Check ending | "file.py".endswith(".py") → True |
replace() | Swap substrings | "hi".replace("hi", "bye") → "bye" |
split() | Break into list | "a,b,c".split(",") → ["a","b","c"] |
join() | Glue list together | ",".join(["a","b"]) → "a,b" |
isdigit() | Only digits? | "123".isdigit() → True |
isalpha() | Only letters? | "abc".isalpha() → True |
isalnum() | Letters or digits? | "abc1".isalnum() → True |
zfill() | Pad with zeros | "42".zfill(5) → "00042" |
You don't need to memorize this table. The important thing is knowing these methods exist so you can look them up when you need them.
What's Next?
In the next tutorial -- [Python String Formatting](/python/python-string-formatting) -- you'll learn how to control exactly how values appear inside strings. You'll master f-string formatting, alignment, number formatting, and more.