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 :
– 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.
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
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 :
- Python program to sort words of a string in alphabetical order
- Python 3 program to check if a string is pangram or not
- Python 3 program to count the total number of characters in a string
- Find total number of lowercase characters in a string using Python 3
- Python program to remove characters from odd or even index of a string
- Python program to replace character in a string with a symbol