The find() function in python helps to return the position of the given substring. If they're more than one occurrence it will return the first occurrence. In case if the searched substring is not found it will return -1.
str.find(sub[, start[, end]] ) #where start & end must be an integers
The find() function takes three parameters. If start and end parameter is missing, it will take zero as starting index and lenght-1 as ending parameter.
|Parameter||Description||Required / Optional|
|sub||The substring whose index has to be found||Required|
|start||Position from where the searching should start in the string. Default is 0||Optional|
|end||Position until the searching should happen. Default is the end of the string||Optional|
The return value is always a integer value specifies the position or index of the substring.This method is similar to index() method,the difference is that index() throws an exception if the searched substring is not found.
|if substring found||index value|
|if not substring found||-1|
string = 'What is the, what is the, what is the' # first occurance of 'what is'(case sensitive) result = string.find('what is') print("Substring 'what is':", result) # find returns -1 if substring not found result = string.find('Hii') print("Substring 'Hii ':", result) # How to use find() in conditions if (string.find('is,') != -1): print("Contains substring 'is,'") else: print("Doesn't contain substring")
Substring 'let it': 13 Substring 'small ': -1 Contains substring 'is,'
string = 'What is your name' # Substring is searched in 'your name' print(string.find('your name', 7)) # Substring is searched in ' is your' print(string.find('is your', 10)) # Substring is searched in 'what is' print(string.find('what is', 8, 16)) # Substring is searched in 'is your' print(string.find('is your ', 0, 14))
8 -1 -1 5