LearnContact
Lesson 1328 min read

String Methods

Explore the most useful built-in string methods in Python for changing case, cleaning up text, splitting and joining, searching, and checking content.

Introduction

In the previous lesson you learned that strings are immutable sequences of characters that support indexing and slicing. Python also ships with dozens of built-in string methods — ready-made functions attached to every string — that make common text tasks effortless.

This lesson focuses on the string methods you will use constantly: changing case, cleaning up whitespace, splitting and joining text, searching for substrings, and checking what kind of characters a string contains.

What You Will Learn
  • How to change the case of text with upper(), lower(), title(), and capitalize().
  • How to remove unwanted whitespace with strip(), lstrip(), and rstrip().
  • How to break text apart with split() and rebuild it with join().
  • How to search and replace text with replace(), find(), and index().
  • How to check the start, end, and content of a string.

What Are String Methods?

A method is a function that belongs to a value and is called using dot notation: string.method(). Since every string in Python is an object of type str, every string automatically has access to the same set of built-in methods.

text = "Hello World"
print(text.lower())
print(text)
Output
hello world
Hello World
Methods Return New Strings

Because strings are immutable, string methods never change the original string — they always return a brand-new string with the result. Notice how text is still "Hello World" after calling text.lower().

Changing Case

Python provides several methods for converting the case of letters in a string.

upper()

Converts every letter to uppercase.

lower()

Converts every letter to lowercase.

title()

Capitalizes the first letter of every word.

capitalize()

Capitalizes only the first letter of the whole string; the rest becomes lowercase.

text = "python IS fun"

print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
Output
PYTHON IS FUN
python is fun
Python Is Fun
Python is fun
Common Use Case

Converting user input to lower() or upper() is a very common way to compare text without worrying about how the user typed it, for example "Yes".lower() == "yes".

Removing Whitespace

Text collected from user input or files often has extra spaces, tabs, or newlines at the edges. The strip(), lstrip(), and rstrip() methods remove that unwanted whitespace.

strip()

Removes whitespace from both the left and right ends.

lstrip()

Removes whitespace only from the left (start) of the string.

rstrip()

Removes whitespace only from the right (end) of the string.

raw = "   Hello, Python!   "

print(repr(raw.strip()))
print(repr(raw.lstrip()))
print(repr(raw.rstrip()))
Output
'Hello, Python!'
'Hello, Python!   '
'   Hello, Python!'
Stripping Specific Characters

All three methods can also take an argument specifying which characters to remove, for example "--Python--".strip("-") returns "Python".

Splitting Strings

The split() method breaks a string into a list of substrings based on a separator. If you do not provide a separator, split() breaks on any whitespace by default.

sentence = "Python is easy to learn"
words = sentence.split()
print(words)

csv_line = "apple,banana,cherry"
fruits = csv_line.split(",")
print(fruits)
Output
['Python', 'is', 'easy', 'to', 'learn']
['apple', 'banana', 'cherry']
Limiting the Splits

split(separator, maxsplit) lets you limit how many splits happen — "a-b-c-d".split("-", 1) returns ["a", "b-c-d"].

Joining Strings

The join() method does the opposite of split() — it combines a list of strings into one string, using the string it is called on as the separator between items.

words = ['Python', 'is', 'easy', 'to', 'learn']
sentence = " ".join(words)
print(sentence)

fruits = ['apple', 'banana', 'cherry']
csv_line = ",".join(fruits)
print(csv_line)
Output
Python is easy to learn
apple,banana,cherry
join() Belongs to the Separator

It is easy to write this backwards. Remember: separator.join(list_of_strings) — the separator (like " " or ",") comes first, and it must already be a string.

Replacing Text

The replace() method returns a new string with every occurrence of one substring swapped out for another.

message = "I like cats. Cats are great."
updated = message.replace("Cats", "Dogs")
print(updated)

limited = message.replace("cats", "dogs", 1)
print(limited)
Output
I like cats. Dogs are great.
I like dogs. Cats are great.

The optional third argument limits how many replacements are made, starting from the left.

Searching: find() and index()

Both find() and index() locate the position of the first occurrence of a substring. The difference is how they handle a substring that is not found.

text = "Python programming"

print(text.find("gram"))
print(text.find("xyz"))
Output
10
-1
text = "Python programming"

print(text.index("gram"))
print(text.index("xyz"))
Output
Traceback (most recent call last):
  ...
ValueError: substring not found
MethodIf Not Found
find()Returns -1
index()Raises a ValueError
Which One Should I Use?

Use find() when the substring might not exist and you want to check safely. Use index() when you are confident the substring is there and want an error if your assumption is wrong.

Checking Start and End

startswith() and endswith() check whether a string begins or ends with a given substring, returning True or False. These are commonly used to check file extensions or filter text.

filename = "report_2026.pdf"

print(filename.startswith("report"))
print(filename.endswith(".pdf"))
print(filename.endswith(".docx"))
Output
True
True
False

Counting Occurrences

The count() method returns how many times a substring appears in a string.

sentence = "the quick brown fox jumps over the lazy dog"
print(sentence.count("the"))
print(sentence.count("o"))
Output
2
4

Checking Character Types

Python provides several methods that check what kind of characters a string is made of, each returning True or False. These are especially useful for validating input.

isalpha()

True if all characters are letters (and the string is not empty).

isdigit()

True if all characters are digits.

isalnum()

True if all characters are letters or digits (no spaces or symbols).

print("Python".isalpha())
print("Python3".isalpha())
print("2026".isdigit())
print("Python3".isalnum())
print("Python 3".isalnum())
Output
True
False
True
True
False
Real-World Use

These checks are often used to validate form input, such as confirming a username contains only letters and numbers with username.isalnum().

Common Mistakes

Avoid These Mistakes
  • Forgetting that string methods return a new string instead of modifying the original.
  • Calling join() on the list instead of the separator, for example words.join(" ") — this is backwards.
  • Using index() when a substring might not exist, causing an unexpected ValueError.
  • Assuming strip() removes spaces from the middle of a string — it only removes them from the edges.
  • Comparing text case-sensitively without first calling lower() or upper() on both sides.

Best Practices

  • Use find() for optional searches and index() only when you expect the substring to exist.
  • Normalize user input with .strip() and .lower() before comparing it.
  • Prefer split() and join() over manual loops when transforming text.
  • Chain methods when it improves readability, like text.strip().lower().
  • Use the is* methods to validate input before processing it further.

Frequently Asked Questions

Do string methods change the original string?

No. Since strings are immutable, every string method returns a brand-new string, leaving the original unchanged.

What is the difference between find() and index()?

find() returns -1 when the substring is not found, while index() raises a ValueError. Choose based on whether "not found" is an expected outcome.

Can split() split on more than one character?

Yes, you can pass any string as the separator, such as "a::b::c".split("::"), which returns ["a", "b", "c"].

How do I check if a string is empty?

Use if not my_string: or check len(my_string) == 0. Note that "".isalpha() returns False because it requires at least one character.

Can I chain multiple string methods together?

Yes. Since each method returns a string, you can chain them, for example " HELLO ".strip().lower() produces "hello".

Key Takeaways

  • String methods are called using dot notation and always return a new string.
  • upper(), lower(), title(), and capitalize() change letter case.
  • strip(), lstrip(), and rstrip() remove unwanted whitespace.
  • split() breaks a string into a list; join() combines a list back into a string.
  • replace() swaps substrings; find() and index() locate them, differing in how they handle a miss.
  • startswith(), endswith(), and count() check and measure substrings.
  • isalpha(), isdigit(), and isalnum() validate what kind of characters a string contains.

Summary

String methods turn Python into a powerful tool for cleaning, transforming, and validating text with very little code. You now have a solid toolkit for case conversion, whitespace cleanup, splitting and joining, searching, and content validation.

Next, you will dive deeper into formatting strings for display, focusing on f-strings — the modern, preferred way to build dynamic text in Python.

Lesson 13 Completed
  • You can change the case of text and clean up whitespace.
  • You can split text apart and join it back together.
  • You can search, replace, and count substrings confidently.
  • You are ready to master f-string formatting.
Next Lesson →

String Formatting (f-Strings)