Every Python String Method Explained with Examples
Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย
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 - it's enough to 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().
HELLO, WORLD! hello, world! Hello, World! Hello, world! HELLO, WORLD!
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.
User said yes! Ada Lovelace
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.
' hello, world! ' 'hello, world!' 'hello, world! ' ' hello, world!'
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.
report.txt https://example.com
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.
7 2 -1 3 11
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.
3 4 0 0
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.
True True False True
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.
I like dogs. Cats are great. I have two dogs. I like dogs. Cats are great. I have two cats.
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).
['Python', 'is', 'easy', 'to', 'learn'] ['Alice', '25', 'New York', 'Engineer'] John Smith Jr.
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.
['home', 'user/documents/report.txt'] ['home/user/documents', 'report.txt']
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.
Python is awesome Python-is-awesome Python, is, awesome Python is awesome
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.
PYTHON IS EASY TO LEARN Alice,25,New York
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.
True False True False True False True False
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.
"player42" is a valid username You entered the number 42
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.
hi ----hi---- hi........ ........hi 00042 007
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.
Item Price ----------------------- Coffee $4.50 Sandwich $8.99 Cookie $2.25 ----------------------- Total $15.74
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.
hello world! hello world!
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!: InvalidPeople type dates in many ways. Write a function to_iso(date_text) that takes a date written month first, such as "7/4/2026", and returns it in the international year-month-day form with two-digit months and days.
to_iso("7/4/2026") # '2026-07-04'
to_iso("12/25/1999") # '1999-12-25'The text may have spaces around it, and the parts may be separated by / or by - ("7-4-2026").
The def line is written for you: put your code under it, indented four spaces, and end with return and your answer. Check calls to_iso() with its own dates, some of them hidden. (Functions get their own lesson later.)
Summary: Python String Methods Cheat Sheet
Here's a quick reference of every method covered in this tutorial:
| Method | What it does | Example |
|---|---|---|
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 - you'll learn how to control exactly how values appear inside strings. You'll master f-string formatting, alignment, number formatting, and more.