Search and Count Methods in Python
Python provides several built-in search and count methods that help us locate substrings or count their occurrences in a given string. These methods are useful for string analysis and text processing.
1. find() Method
Searches the string for a specified value and returns
the index of the first occurrence. Returns -1 if not found.
We can also specify the start and end
positions to limit the search to a specific portion of the string.
Syntax:
string.find(substring, start, end)
Example:
text = "learning python is fun"
print(text.find("python"))
print(text.find("java"))
print(text.find("python", 0, 10)) # searches from index 0 to 9
Output:
9
-1
-1
Explanation:
"python"starts at index 9."java"is not found, so it returns-1.- Third time, it searches only from index 0 to 9, so
"python"is not found →-1.
2. rfind() Method
Returns the highest index (last occurrence)
of the specified substring. Returns -1 if not found.
Syntax:
string.rfind(substring, start, end)
Example:
text = "abc abc abc"
print(text.rfind("abc"))
Output:
8
Explanation:
- The substring
"abc"appears three times. rfind()gives the index of the last one: index 8.
3. index() Method
Same as find(), but raises a
ValueError if not found instead of returning -1.
Syntax:
string.index(substring, start, end)
Example:
text = "python programming"
print(text.index("programming"))
Output:
7
Explanation:
"programming"starts from index 7.- If the substring is not found, it will throw an error instead of returning -1.
4. rindex() Method
Same as rfind(), but raises a
ValueError if not found.
Syntax:
string.rindex(substring, start, end)
Example:
text = "abc def abc"
print(text.rindex("abc"))
Output:
8
Explanation:
rindex()works just likerfind()but throws error if not found.- Last occurrence of
"abc"is at index 8.
5. count() Method
Returns the number of times a specified value occurs in the string.
Syntax:
string.count(substring, start, end)
Example:
text = "banana"
print(text.count("a"))
Output:
3
Explanation:
- The character
'a'appears 3 times in the word"banana". count()helps in frequency analysis of substrings.
String Searching and Counting Methods - Summary Table:
| Method | Purpose | Returns | If Not Found |
|---|---|---|---|
find() |
Finds the first occurrence of a substring (within optional range) | Index of first match | -1 |
rfind() |
Finds the last occurrence of a substring (within optional range) | Index of last match | -1 |
index() |
Same as find(), but raises error if not found |
Index of first match | ValueError |
rindex() |
Same as rfind(), but raises error if not found |
Index of last match | ValueError |
count() |
Counts how many times a substring occurs (within optional range) | Number of occurrences | 0 |