The find() method of the Python string returns the first matched index of the substring. It returns -1 if not found.
The syntax of the method is: str.find(s, sub[, start[, end]])
Key Points :
• If the string contains a substring, this function returns the index for the first string occurrence; if the substring does not exist in a string, the function returns -1.
• String find() function helps to find the substring index within a string.
• If the start and end index of a string is not set in any situation, the default value of start is 0, and the string length shall assume to be -1.
• The find() String method often returns an integer value.
• This approach may use to locate both a substring and a string letter.
We’ll be covering the following topics in this tutorial:
Parameters for the find() method
The function find() takes up to three parameters:
• sub – This is the substring to be looked for.
• start and end (optional) – the str[start: end] set for which the substring has scanned.
Return Value from find() method
This find() string returns an integer value.
• If there is the substring or letter we are searching for in the string, this method would then return an index of the first occurrence of a substring or letter.
• If the substring or a letter in that string does not occur, then the method returns -1 in that situation.
Below is the python program to demonstrate the find() function:
str_a = "The Best Learning Resource for Online Education"; str_b = "Online"; print (str_a.find(str_b)) print (str_a.find(str_b, 35)) print (str_a.find(str_b, 40))
When we run above the program, the outcome is as follows:
31
-1
-1
How can python find index of character in string?
There are two string methods in python find index of character in string, find() and index(). The distinction between the two is whether the search string is not found. find() returns -1 and index() raises ValueError.
str = 'The Best Learning Resource for Online Education' result = str.find('E') print(result)
When we run above the program, the outcome is as follows:
38
In the above output we find index of character in string python is 38.
Below are several other functions that we can use to work with string in Python 3