Home »
Python
Python String find() Method
By IncludeHelp Last updated : December 15, 2024
Python String find() Method
The find() is an inbuilt method of python, it is used to check whether a sub-string exists in the string or not. If sub-string exists, the method returns the lowest index of the sub-string, if sub-string does not exist, method return -1.
Note: This method is case sensitive.
Syntax
String.find(sub_string[, start_index[, end_index]])
Parameters
- sub_string - a part of the string to be found in the string.
- start_index - an optional parameter, it defines the starting index from where sub_string should be found.
- end_index - an optional parameter, it defines end index of the string. Find method will find the sub_string till this end_index.
Return Value
- Returns the lowest index of the sub_string, if it exits in the string.
- Returns -1 if sub_string does not exist in the string.
Example 1
# string in which we have to find the sub_string
str = "Hello world, how are you?"
# sub_string to find the given string
sub_str = "how"
# find by sub_str
print (str.find (sub_str))
# find by sub_str with slice:start index
print (str.find (sub_str, 10))
# find by sub_str with slice:start index and slice: end index
print (str.find (sub_str, 10, 24))
# find a sub_str that does not exist
sub_str = "friend"
# find by sub_str
print (str.find (sub_str))
# find a sub_str with different case
sub_str = "HOW"
# find by sub_str
print (str.find (sub_str))
Output
13
13
13
-1
-1
Example 2
str1 = "Hello, welcome to the world of Python"
result1 = str1.find("welcome")
print(result1)
str2 = "Hello, Python!"
result2 = str2.find("Java")
print(result2)
str3 = "Python programming is fun"
result3 = str3.find("Python")
print(result3)
str4 = "Hello"
result4 = str4.find("o")
print(result4)
Output
7
-1
0
4