Python String find() method
Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1.
Syntax: str_obj.find(sub, start, end)
- sub: Substring that needs to be searched in the given string.
- start (optional): Starting position where the substring needs to be checked within the string.
- end (optional): End position is the index of the last value for the specified range. It is excluded while checking.
Return: Returns the lowest index of the substring if it is found in a given string. If it’s not found then it returns -1.
Python String find() method Example
- If the start and end indexes are not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search.
- The find() method is similar to index(). The only difference is find() returns -1 if the searched string is not found and index() throws an exception in this case.
Example 1: find() With No start and end Argument
Substring 'geeks' found at index: 0 Substring 'for ' found at index: 6 Doesn't contains given substring
Example 2: find() With start and end Arguments
10 -1 -1 6
- In the first statement, the output is 10 as the start value is given which is 2, so the substring is checked from the second index which is ‘eks for geeks’.
- In the second statement, the start value is given as 2 and the substring is given ‘geeks’, so the index position of ‘geeks’ is 10 but due to the last value is being excluded it will only find ‘geek’ which doesn’t matches with the original string, that is why the output is -1.
- In the third statement, start value=4, end value=10, and substring = ‘g’ is given, the index position from 4 will be checked for the given substring which is at position 10, which is being excluded as it is the end index.
- In the fourth statement, start value =4, end value=11, and substring=’for’ is given, the index position from 4 till 11 will be checked for the given substring and the specified substring is present at index 6, so the output is obtained.