Python String find() Method
find() method in Python returns the index of the first occurrence of a substring within a given string. If the substring is not found, it returns -1. This method is case-sensitive, which means "abc" is treated differently from "ABC". Example:
s = "Welcome to GeekforGeeks!"
index = s.find("GeekforGeeks")
print(index)
Output
11
Explanation: The substring "GeeksforGeeks" starts at index 11 in the string "Welcome to GeeksforGeeks!". Hence, find() method returns 11
Syntax of find() method
s.find(substring, start, end))
Parameter:
- substring: The substring to search for within the main string s.
- start (optional): The starting index from where to begin the search.
- end (optional): The ending index where the search should stop.
Return Value:
- Returns the first index of the substring if it is found within the specified range.
- Returns -1 if the substring is not found.
Examples of find() method
Example 1: We can limit the search to a specific portion of the string by providing start and end parameters.
s = "abc abc abc"
index = s.find("abc", 4)
print(index)
Output
4
Explanation:
- The search starts from index 4, skipping the first "abc".
- The next occurrence of "abc" is found at index 8.
Example 2: The find() method is case-sensitive, so uppercase and lowercase letters are treated differently.
s = "Python is fun"
index = s.find("python")
print(index)
Output
-1
Explanation: Since "python" (lowercase) does not match "Python" (uppercase), the method returns -1.
Example 3: In this example, we are searching for the first occurrence of a substring "abc" in a string that contains multiple spaces between the words.
s = "abc abc abc"
res = s.find("abc")
print(res)
Output
0
Explanation: The substring "abc" starts at index 0 in the string "abc abc abc", so find() returns 0.
find() vs index()
Both find() and index() methods locate a substring within a string. However, they differ in behavior when the substring is not found.
- find() returns the index or -1 if not found
- index() same as find(), but raises a ValueError if not found
To learn more, please refer to "Difference Between find( ) and index( ) in Python".
Related Articles:
- Check if String Contains Substring in Python
- Python | Check if substring present in string
- Python | Find position of a character in given string
- Python String Methods