Master Python's String.find() Method: Syntax, Examples & Alternatives
What is Python String.find()?
The String.find() method in Python returns the index of the first occurrence of a specified substring within a string. If the substring isn’t found, it gracefully returns -1 instead of raising an exception, making it a convenient choice for substring searches.
In this guide, you’ll learn how to use find() effectively, explore its parameters, compare it with related methods, and even count how many times a substring appears.
- Understanding String.find()
- Syntax and parameters
- Using default arguments
- Specifying a start index
- Defining a start and end range
- Finding positions of substrings
- Comparing with rfind()
- Comparing with index()
- Counting substring occurrences
Syntax of Python string find()
The method’s signature is straightforward:
string.find(substring, start, end)
Parameters
- substring – The text you’re searching for.
- start (optional) – Index where the search begins; defaults to
0. - end (optional) – Index where the search ends; defaults to the string’s length.
Using find() with Default Values
When no start or end is provided, find() scans the entire string from the beginning. It returns the index of the first match or -1 if none is found.
Example:
mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials is at:", mystring.find("Tutorials"))
Output:
The position of Tutorials is at: 12
Specifying a Start Index
Providing a start argument limits the search to begin at that position, extending to the string’s end.
Example:
mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials is at:", mystring.find("Tutorials", 20))
Output:
The position of Tutorials is at 48
Defining a Start and End Range
By supplying both start and end, you can confine the search to a specific slice of the string.
Example:
mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials is at:", mystring.find("Tutorials", 5, 30))
Output:
The position of Tutorials is at 12
Finding Positions and Handling Missing Substrings
Here’s how find() behaves when the substring is present and when it’s absent.
Example:
mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Best site is at:", mystring.find("Best site", 5, 40))
print("The position of Guru99 is at:", mystring.find("Guru99", 20))
Output:
The position of Best site is at: 27 The position of Guru99 is at: -1
Comparing with rfind()
rfind() is similar to find() but returns the highest index where the substring occurs. If the substring isn’t present, both methods return -1.
Example:
mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials using find() : ", mystring.find("Tutorials"))
print("The position of Tutorials using rfind() : ", mystring.rfind("Tutorials"))
Output:
The position of Tutorials using find() : 12 The position of Tutorials using rfind() : 48
Comparing with index()
The index() method behaves like find() but raises a ValueError when the substring is missing.
Example:
mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials using find() : ", mystring.find("Tutorials"))
print("The position of Tutorials using index() : ", mystring.index("Tutorials"))
Output:
The position of Tutorials using find() : 12 The position of Tutorials using index() : 12
When the substring isn’t found:
mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials using find() : ", mystring.find("test"))
print("The position of Tutorials using index() : ", mystring.index("test"))
Output:
The position of Tutorials using find() : -1
Traceback (most recent call last):
File "task1.py", line 3, in <module>
print("The position of Tutorials using index() : ", mystring.index("test"))
ValueError: substring not found
Counting Substring Occurrences
To tally how many times a substring appears, iterate through the string and repeatedly call find() with an updated start index.
Example:
my_string = "test string test, test string testing, test string test string"
startIndex = 0
count = 0
for _ in range(len(my_string)):
k = my_string.find('test', startIndex)
if k != -1:
startIndex = k + 1
count += 1
print("The total count of substring test is:", count)
Output:
The total count of substring test is: 6
Key Takeaways
find()returns the first matching index or-1if absent.- Parameters:
substring, optionalstart(default 0), optionalend(default string length). - Use
startto begin the search at a specific position. - Use
startandendto limit the search to a substring slice. rfind()returns the last matching index.index()is stricter, raising an error when the substring is missing.- Looping with
find()can count total occurrences.
Python
- Java String length() Method: How to Get a String’s Size (Example)
- Mastering Java String.indexOf(): Locating Substrings & Practical Examples
- Master Python’s str.count(): How to Count Characters & Substrings with Examples
- Master Python `format()` Strings with Clear Examples
- Python round() Function Explained with Practical Examples
- Mastering Python's map() Function: Syntax, Examples, and Best Practices
- Python timeit() – Measuring Execution Time with Practical Examples
- Mastering Python’s readline() – Efficient Line‑by‑Line File Reading
- Python list.count(): Expert Guide with Practical Examples
- Python Module Importing – A Practical Guide with Examples