Skip to main content
Editor

Every Python String Method Explained with Examples

Beginner25 min7 exercises130 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

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

All five case methods
greeting = "hello, world!"
print(greeting.upper()) # HELLO, WORLD!
print(greeting.lower()) # hello, world!
print(greeting.title()) # Hello, World!
print(greeting.capitalize()) # Hello, world!
print(greeting.swapcase()) # HELLO, WORLD!
Output
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.

Practical case method usage
# Real-world use: case-insensitive comparison
user_input = "Yes"
# Without lower(), "Yes" != "yes" and your check fails
if user_input.lower() == "yes":
print("User said yes!")
# title() is great for formatting names
full_name = "ada lovelace"
print(full_name.title()) # Ada Lovelace
Output
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.

strip(), lstrip(), and rstrip()
messy = " hello, world! "
print(repr(messy)) # ' hello, world! '
print(repr(messy.strip())) # 'hello, world!'
print(repr(messy.lstrip())) # 'hello, world! '
print(repr(messy.rstrip())) # ' hello, world!'
Output
'   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.

Stripping specific characters
# You can also strip specific characters
filename = "###report.txt###"
print(filename.strip("#")) # report.txt
url = "https://example.com/"
print(url.rstrip("/")) # https://example.com
Output
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.

find() returns the position of a substring
sentence = "I love Python programming"
print(sentence.find("Python")) # 7 (starts at position 7)
print(sentence.find("love")) # 2
print(sentence.find("Java")) # -1 (not found)
print(sentence.find("o")) # 3 (first occurrence)
print(sentence.find("o", 4)) # 11 (search starting from position 4)
Output
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.

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
text = "the cat sat on the mat by the hat"
print(text.count("the")) # 3
print(text.count("at")) # 4 (cat, sat, mat, hat)
print(text.count("dog")) # 0
print(text.count("The")) # 0 (case-sensitive!)
Output
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.

startswith() and endswith()
filename = "report_2024.pdf"
print(filename.startswith("report")) # True
print(filename.endswith(".pdf")) # True
print(filename.endswith(".txt")) # False
# Check multiple options with a tuple
print(filename.endswith((".pdf", ".docx", ".txt"))) # True
Output
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.

replace() swaps substrings
message = "I like cats. Cats are great. I have two cats."
# Replace all occurrences
print(message.replace("cats", "dogs"))
# I like dogs. Cats are great. I have two dogs.
# Notice "Cats" (capital C) was NOT replaced -- case matters!
# Limit replacements with the third argument
print(message.replace("cats", "dogs", 1))
# I like dogs. Cats are great. I have two cats.
Output
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).

split() breaks strings into lists
sentence = "Python is easy to learn"
words = sentence.split()
print(words) # ['Python', 'is', 'easy', 'to', 'learn']
# Split on a specific character
csv_line = "Alice,25,New York,Engineer"
values = csv_line.split(",")
print(values) # ['Alice', '25', 'New York', 'Engineer']
# Split with a limit
first, rest = "John Smith Jr.".split(" ", 1)
print(first) # John
print(rest) # Smith Jr.
Output
['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.

rsplit() splits from the right
path = "home/user/documents/report.txt"
# split from the left
print(path.split("/", 1)) # ['home', 'user/documents/report.txt']
# rsplit from the right
print(path.rsplit("/", 1)) # ['home/user/documents', 'report.txt']
Output
['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.

join() glues strings together
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Python is awesome
# Use any separator you want
print("-".join(words)) # Python-is-awesome
print(", ".join(words)) # Python, is, awesome
print("\n".join(words)) # Each word on its own line
Output
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.

Split, modify, and rejoin
# Uppercase every word, then rejoin
sentence = "python is easy to learn"
words = sentence.split()
capitalized = [word.upper() for word in words]
result = " ".join(capitalized)
print(result) # PYTHON IS EASY TO LEARN
# Build a CSV line from data
fields = ["Alice", "25", "New York"]
csv_line = ",".join(fields)
print(csv_line) # Alice,25,New York
Output
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.

isalpha(), isdigit(), isalnum(), isspace()
print("hello".isalpha()) # True (only letters)
print("hello1".isalpha()) # False (contains a digit)
print("12345".isdigit()) # True (only digits)
print("12.5".isdigit()) # False (dot is not a digit)
print("hello1".isalnum()) # True (letters and digits only)
print("hello!".isalnum()) # False (! is not alphanumeric)
print(" ".isspace()) # True (only whitespace)
print(" hi ".isspace()) # False (contains letters)
Output
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.

Using check methods for validation
# Practical example: validate a username
username = "player42"
if username.isalnum():
print(f"\"{username}\" is a valid username")
else:
print(f"\"{username}\" contains invalid characters")
# Check if user typed a number
user_input = "42"
if user_input.isdigit():
number = int(user_input)
print(f"You entered the number {number}")
else:
print("That's not a valid number")
Output
"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.

center(), ljust(), rjust(), and zfill()
word = "hi"
print(word.center(10)) # " hi "
print(word.center(10, "-")) # "----hi----"
print(word.ljust(10, ".")) # "hi........"
print(word.rjust(10, ".")) # "........hi"
# zfill() pads with zeros on the left
print("42".zfill(5)) # 00042
print("7".zfill(3)) # 007
Output
    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.

Building a formatted table
# Build a neat table
print("Item".ljust(15) + "Price".rjust(8))
print("-" * 23)
print("Coffee".ljust(15) + "$4.50".rjust(8))
print("Sandwich".ljust(15) + "$8.99".rjust(8))
print("Cookie".ljust(15) + "$2.25".rjust(8))
print("-" * 23)
print("Total".ljust(15) + "$15.74".rjust(8))
Output
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.

Chaining methods together
user_input = " Hello, World! "
# Chain multiple methods together
cleaned = user_input.strip().lower().replace(",", "")
print(cleaned) # hello world!
# Same thing step by step:
step1 = user_input.strip() # "Hello, World!"
step2 = step1.lower() # "hello, world!"
step3 = step2.replace(",", "") # "hello world!"
print(step3) # hello world!
Output
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.

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
user_input = " HeLLo PyThOn "
# Clean up the input and print it
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".

sentence = "The cat sat on the mat by the door and The dog watched"
# Count how many times "the" appears and print it
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.
sentence = "I love JavaScript. JavaScript is great. Learning JavaScript is fun."
# Replace JavaScript with Python and print it
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
csv_line = "Alice,25,New York,Engineer"
# Split the line by commas and print each value
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?

    sentence = "I love Python programming"
    # Find "Python" -- this line works fine
    pos = sentence.index("Python")
    print(f"Found at position {pos}")
    # Find "Java" -- this line crashes!
    pos = sentence.index("Java")
    if pos >= 0:
    print(f"Found at position {pos}")
    else:
    print("Word not found")
    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
    usernames = ["player42", "ab", "hello world!"]
    # Check each username and print if it's valid or invalid
    Tidy Dates
    Stretch

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

    def to_iso(date_text):
    pass
    Solution unlocks after your first Check

    Summary: Python String Methods Cheat Sheet

    Here's a quick reference of every method covered in this tutorial:

    MethodWhat it doesExample
    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.

    Harder problems

    More problems on this topic: Strings

    Related Tutorials

    Was this tutorial helpful?