Python program to find a substring in a string

Python program to find a substring in a string using find() :

find() method in python is used to find out a substring in a string. This method will find the index of a substring in a string and returns the index of the first occurance of the substring. If the substring is not found, it will return -1.
The syntax of the method is as below :

str.find(substring,startIndex,endIndex)

substring is the sub-string to find in the str string.
startIndex is the starting index of the string where the search should begin.
endIndex is the end index of the string i.e. where the search should stop.

Example :

Let me show you with an example how it works :

given_str = "The quick brown fox jumps over the lazy dog"

print(given_str)

sub_string = input("Enter a sub-string to find in the above string : ")

if(given_str.find(sub_string) == -1):
    print("The substring doesn't contain in the string")
else:
    print("The substring is found on position : ",given_str.find(sub_string))

Sample Output :

The quick brown fox jumps over the lazy dog
Enter a sub-string to find in the above string : quick
The substring is found on position :  4

The quick brown fox jumps over the lazy dog
Enter a sub-string to find in the above string : hello
The substring doesn't contain in the string

Conclusion :

In this tutorial, we have learn how to find one substring in a string in python using the find() method. Try to run the above example and also try to find substring in a given range by passing the startIndex and endIndex to the find() method.

You might also like :

Leave a Reply