Skip to main content

Every Python String Method Explained with Examples

Beginner25 min6 exercises100 XP
0/6 exercises

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().

All five case methods
Loading editor...

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.

Practical case method usage
Loading editor...

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(), lstrip(), and rstrip()
Loading editor...

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.

Stripping specific characters
Loading editor...

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.

find() returns the position of a substring
Loading editor...

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.

find() -- returns -1 if not found
text = "hello world"
result = text.find("xyz")
print(result)  # -1 (safe, no crash)
index() -- raises error if not found
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)  # 6

How 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.

count() counts substring occurrences
Loading editor...

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.

startswith() and endswith()
Loading editor...

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.

replace() swaps substrings
Loading editor...

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

split() breaks strings into lists
Loading editor...

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.

rsplit() splits from the right
Loading editor...

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.

join() glues strings together
Loading editor...

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.

Split, modify, and rejoin
Loading editor...

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(), isdigit(), isalnum(), isspace()
Loading editor...

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.

Using check methods for validation
Loading editor...

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(), ljust(), rjust(), and zfill()
Loading editor...

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.

Building a formatted table
Loading editor...

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.

Chaining methods together
Loading editor...

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.

Exercise 1: Clean Up User Input
Write Code

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 python
Loading editor...
Exercise 2: Count Word Occurrences
Write Code

Count 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 times

Hint: Convert to lowercase first so you catch both "the" and "The".

Loading editor...
Exercise 3: Replace All Occurrences
Write Code

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.
Loading editor...
Exercise 4: Split a CSV Line
Write Code

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
Engineer
Loading editor...
Exercise 5: Fix the Bug -- find() vs index()
Fix the Bug

This 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:

  • Prints the position when the word is found
  • Prints "Word not found" when the word is missing
  • Expected output:

    Found at position 7
    Word not found

    Hint: The bug is that index() crashes when the word is missing. Which method returns -1 instead of crashing?

    Loading editor...
    Exercise 6: Validate a Username
    Write Code

    Write a program that validates a username based on these rules:

  • Must be alphanumeric (letters and numbers only)
  • Must be between 3 and 15 characters long
  • 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!: Invalid
    Loading editor...

    Summary: 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.