Examples for string find in Python
Categories:
Mastering String Search in Python: The 'find()' Method Explained

Explore Python's find()
method for efficient substring searching, understand its parameters, return values, and practical applications with clear examples.
Python offers several ways to search for substrings within a larger string. Among the most common and straightforward is the built-in find()
method. This article will delve into the find()
method, explaining its functionality, parameters, and how to use it effectively in your Python projects. We'll cover basic usage, searching within specific ranges, and handling cases where the substring is not found.
Understanding Python's str.find()
Method
The str.find()
method is a powerful tool for locating the first occurrence of a specified substring within a given string. It returns the lowest index in the string where the substring is found. If the substring is not found, find()
returns -1. This behavior makes it distinct from str.index()
, which raises a ValueError
if the substring is not present.
flowchart TD A[Start: Call str.find(sub, start, end)] --> B{Is 'sub' found in 'str'?} B -- Yes --> C[Return lowest index of 'sub'] B -- No --> D[Return -1] C --> E[End] D --> E[End]
Flowchart of the str.find()
method logic
Basic Usage of find()
The simplest form of find()
takes only one argument: the substring you want to search for. It will scan the entire string from the beginning and return the index of the first match.
text = "Hello, world! Welcome to Python programming."
# Find the first occurrence of 'world'
index1 = text.find("world")
print(f"'world' found at index: {index1}")
# Find a substring that doesn't exist
index2 = text.find("java")
print(f"'java' found at index: {index2}")
# Case-sensitive search
index3 = text.find("python")
print(f"'python' (lowercase) found at index: {index3}")
index4 = text.find("Python")
print(f"'Python' (uppercase) found at index: {index4}")
Basic examples of str.find()
As you can see, find()
is case-sensitive. If you need a case-insensitive search, you'll typically convert both the main string and the substring to the same case (e.g., lowercase) before performing the search.
Searching Within a Specific Range
The find()
method also accepts optional start
and end
parameters, allowing you to specify a slice of the string to search within. This is particularly useful when you want to find multiple occurrences of a substring or limit your search to a particular segment of a larger text.
long_text = "Python is fun. Python is powerful. Python is versatile."
# Search from a specific starting index
first_python = long_text.find("Python")
print(f"First 'Python' found at: {first_python}")
# Search for the next 'Python' after the first one
second_python = long_text.find("Python", first_python + 1)
print(f"Second 'Python' found at: {second_python}")
# Search within a defined range (e.g., from index 10 to 30)
range_search = long_text.find("is", 10, 30)
print(f"'is' found in range [10, 30) at: {range_search}")
# Search in a range where the substring is not present
not_found_in_range = long_text.find("fun", 20, 40)
print(f"'fun' not found in range [20, 40) returns: {not_found_in_range}")
Using start
and end
parameters with find()
start
parameter is inclusive, and the end
parameter is exclusive. This means the search will occur in the slice s[start:end]
.Distinction from str.index()
While find()
and index()
both locate substrings, their behavior when a substring is not found is a critical difference. find()
returns -1, which can be easily checked in conditional statements. index()
, on the other hand, raises a ValueError
, requiring error handling with try-except
blocks.
my_string = "apple banana cherry"
# Using find()
find_result = my_string.find("grape")
if find_result == -1:
print("Using find(): 'grape' not found.")
else:
print(f"Using find(): 'grape' found at index {find_result}.")
# Using index()
try:
index_result = my_string.index("grape")
print(f"Using index(): 'grape' found at index {index_result}.")
except ValueError:
print("Using index(): 'grape' not found (ValueError caught).")
Comparing find()
and index()
behavior
find()
when you want to gracefully handle cases where a substring might not exist without interrupting program flow. Use index()
when the absence of a substring indicates an exceptional condition that should halt execution or be explicitly handled as an error.