Python String find() Method

The find() method returns the index of the first occurence of a substring in the given string (case-sensitive). If the substring is not found it returns -1.

Syntax:

str.find(substr, start, end)

Parameters:

  1. substr: (Required) The substring whose index has to be found.
  2. start: (Optional) The starting index position from where the searching should start in the string. Default is 0.
  3. end: (Optional) The ending index position untill the searching should happen. Default is end of the string.

Return Value:

Returns an integer value indicating an index of the first occurence of the specified substring.

The following examples demonstrates find() method.

Example: find()
greet='Hello World!'
print("Index of 'H': ", greet.find('H'))
print("Index of 'h': ", greet.find('h')) # returns -1 as 'h' no found
print("Index of 'e': ", greet.find('e'))
print("Index of 'World': ", greet.find('World'))
Output
Index of 'H':  0
Index of 'h':  -1
Index of 'e':  1
Index of 'World':  6

The find() method returns an index of the first occurence only.

Example: find()
greet='Hello World'
print('Index of l: ', greet.find('l'))
print('Index of o: ', greet.find('o'))

mystr='tutorialsteacher is a free tutorials website'
print('Index of tutorials: ', mystr.find('tutorials'))
Output
Index of l:  2
Index of o:  4
Index of tutorials:  0

The find() method performs case-sensitive search. It returns -1 if a substring is not found.

Example: find()
greet='Hello World'
print(greet.find('h'))  
print(greet.find('hello')) 
print(greet.find('Hi')) 
Output
-1
-1
-1

Use start and end parameters to limit the search of a substring between the specified starting and ending index, as shown below.

Example: find() with start and end
mystr='tutorialsteacher is a free tutorials website'
print(mystr.find('tutorials', 10)) # search starts from 10th index
print(mystr.find('tutorials', 1, 26)) # searches between 1st and 26th index
Output
27
-1
Want to check how much you know Python?