Python String Searching

In the last lesson, we learned about Python String Formatting. Now let’s find words and characters inside existing text.

Let’s Talk About Finding Things in Text

We have a string. Maybe it is a long message. Maybe it is a document. And we want to find something inside it.

Maybe we want to know if a word appears. Maybe we want to know where it appears. Maybe we want to count how many times it appears.

That is what string searching is about. Python gives us several tools to search inside strings. Let’s go through them.

The in Operator in Python Strings

The simplest way to check if something is inside a string is with in.

message = "Hello, world!"
print("world" in message)

Output

True

It returns True if the substring is found. False if not.

print("python" in message)

Output

False

We can also use not in to check the opposite.

print("python" not in message)

Output

True

This is the quickest and most readable way to check if something exists. Let’s use it when we just need a yes or no answer.

The find() Method in Python Strings

If we want to know where the substring is, we use find().

It returns the index of the first occurrence. If not found, it returns -1.

message = "Hello, world!"
print(message.find("world"))

Output

7

Because “world” starts at index 7.

print(message.find("python"))

Output

-1

We can also specify a start and end index to search within a slice.

message = "Hello, world! Hello again!"
print(message.find("Hello", 5))

Output

14

It starts searching from index 5. So it skips the first “Hello” at index 0. And finds the second one at index 14.

The rfind() Method in Python Strings

rfind() is like find(), but it searches from the right. It returns the last occurrence.

message = "Hello, world! Hello again!"
print(message.rfind("Hello"))

Output

14

It finds the last “Hello” instead of the first.

The index() Method in Python Strings

index() is like find(). But if the substring is not found, it raises a ValueError instead of returning -1.

message = "Hello, world!"
print(message.index("world"))

Output

7
print(message.index("python"))

Output

ValueError: substring not found

Let’s use index() when we are sure the substring exists. Otherwise, use find() and check for -1.

The rindex() Method in Python Strings

rindex() is like rfind(). It searches from the right and returns the last occurrence. But it raises an error if not found.

message = "Hello, world! Hello again!"
print(message.rindex("Hello"))

Output

14

The count() Method in Python Strings

count() tells us how many times a substring appears.

message = "banana"
print(message.count("a"))

Output

3

We can also count a substring.

message = "Hello, world! Hello again!"
print(message.count("Hello"))

Output

2

We can specify a start and end index.

print(message.count("Hello", 5))

Output

1

That counts “Hello” only after index 5. So it only finds the second one.

Checking Start and End in Python Strings

Sometimes we only care if the string starts or ends with something.

Let’s use startswith() and endswith().

filename = "report.pdf"
print(filename.startswith("report"))

Output

True
print(filename.endswith(".pdf"))

Output

True

These are very useful for checking file extensions, prefixes, and more.

Python String Searching: A Real-Life Example

Let’s search a log file for errors.

log = """
2025-01-15 10:00:00 INFO Starting process
2025-01-15 10:00:01 ERROR Something went wrong
2025-01-15 10:00:02 INFO Process finished
"""
if "ERROR" in log:
print("An error was found in the log")
position = log.find("ERROR")
print(f"Error starts at index {position}")
else:
print("No errors found")

Output

An error was found in the log
Error starts at index 51

That is a simple way to scan text for problems.

Another Example — Counting Words

sentence = "the quick brown fox jumps over the lazy dog"
word = "the"
count = sentence.count(word)
print(f"The word '{word}' appears {count} times")

Output

The word 'the' appears 2 times

But let’s be careful. This counts “the” inside “there” or “other” too. For word-level counting, we would need to split the sentence into words first.

words = sentence.split()
count = words.count("the")
print(f"The word 'the' appears {count} times")

Output

The word 'the' appears 2 times

That is more accurate.

Case Sensitivity in Python String Searching

All these methods are case sensitive.

message = "Hello, world!"
print(message.find("hello"))

Output

-1

Because “hello” is lowercase, but the string has “Hello” with a capital H.

If we want to ignore case, we convert both to lowercase first.

message = "Hello, world!"
print(message.lower().find("hello"))

Output

0

That works.

Common Mistakes with Python String Searching

Mistake 1: Using find() and Forgetting It Returns -1

message = "Hello"
if message.find("xyz"):
print("Found")

This will print “Found” even though it is not found. Because -1 is truthy. Let’s always check against -1.

if message.find("xyz") != -1:
print("Found")

Or better, use in.

if "xyz" in message:
print("Found")

Mistake 2: Using index() When the Substring Might Not Exist

message = "Hello"
print(message.index("xyz"))

This raises an error. Let’s use find() if we are not sure.

Mistake 3: Forgetting Case Sensitivity

filename = "Report.PDF"
print(filename.endswith(".pdf"))

Output

False

Because of the uppercase PDF. So what do we do? We use .lower() first.

print(filename.lower().endswith(".pdf"))

Output

True

Mistake 4: Using count() for Word Count Without Splitting

sentence = "theater"
print(sentence.count("the"))

Output

1

But “the” is not a word here. It is part of “theater”. So let’s split first if we need exact words.

Next, we will learn about Python String Replacement and replace selected text with new content.