String find() is a in-build method in python use to find sub-string in string, if sub-string is already present in the string then it returns the first index of string else it return (-1).
Syntax:
string.find(sub_string, start_index, end_index)
Parameters :
string: Our primary string (Required)
sub_string: sub-string which need to be searched in the primary string (Required)
start_index: Start index from where to search for sub-string (Optional)
end_index: End index where to search for the sub-string (Optional)
Returns: Returns the first index of the sub-string if its found in given string
Note:
1.Returns first occurrence of sub-string.
2.If first and last arguments are not given it will take 0 as first and -1 as last argument.
3.If only one argument is given then it will take it as start argument and -1 as end argument.
4.It is case-sensitive.
5.If sub-string not find in the string then it returns -1
Example:
# Python program to explain find() method
sstr = 'Welcome to STechies: Smart Techies'
# Returns first occurrence of Substring
sub = sstr.find('STechies')
print ("Stechies is at :", sub )
# find() method is case-sensitive
sub = sstr.find('stechies')
print ("Stechies is at :", sub )
# Returns -1 if substring not present in string
sub = sstr.find('Hello')
print ("Hello is at :", sub )
# find method with start and end Arguments
sub2 = sstr.find('Smart', 10, 30)
print ("Smart is at :", sub2 )
# If only One argument given
# It will take it as start Agrument
sub2 = sstr.find('Smart', 10)
print ("Smart is at :", sub2 )
Output:
Stechies is at : 11
Stechies is at : -1
Hello is at : -1
Smart is at : 21
Smart is at : 21
Real Life example:
# Program to explain find function
sstr = 'Welcome to STechies: Smart Techies'
if (sstr.find('STechies') != -1):
print ("STechies found in given string")
else:
print ("STechies Not found in given string")
Output:
STechies found in given string