Python String | find()



Syntax:

str.find (sub, start, end)

Parameters :

sub: It`s the substring which needs to be searched in the given string.
start: Starting position where sub is needs to be checked within the string.
end: Ending position where suffix is ​​needs to be checked within the string.

NOTE. If no start and end indices are supplied, then it defaults to 0 and length-1 as start and end indices, where end indices are not included in our search.

Returns:

returns the lowest index of the substring if it is found in given string. If it`s not found then it returns -1.

CODE 1

 

word = `geeks for geeks`

  
# returns the first occurrence of Substring

result = word.find ( ` geeks` )

print ( "Substring` geeks` found at index : " , result)

  

result = word.find ( `for ` )

print ( "Substring` for `found at index:" , result)

  
# How to use find ()

if (word.find ( `pawan` )! = - 1 ):

  print ( "Contains given substring" )

else :

print ( "Doesn`t contains given substring" )

Output:

 Substring `geeks` found at index: 0 Substring` for `found at index: 6 Doesn`t contains given substring 

Code 2

word = `geeks for geeks`

  
# The substring is searched for in & # 39; eks for geeks & # 39;

print (word.find ( `ge` , 2 )) 

 
# The substring is searched for in & # 39; eks for geeks & # 39;

print (word.find ( ` geeks ` , 2 )) 

  
# The substring is searched for in & # 39; s for g & # 39;

print (word.find ( `g` , 4 , 10 )) 

 
# The substring is searched for in & # 39; s for g & # 39;

print (word.find ( `for ` , 4 , 11 )) 

Output:

 10 -1 -1 6