Pythons find() Method: How to Search for Substrings within a String?

Last updated on January 24, 2023

The find() method finds the specified word or substring into a string and returns the index of its first character. In case if it doesn’t find the substring then it returns -1

Example 1:

For example, if you search the word “is” in “Time is Money” you will get 5. Because the first letter of “is” is “i” and its index position is 5.

hayStack = "Time is Money"
indexPosition = hayStack.find("is")
print(indexPosition)
# Output: 5

In this example, we have a variable hayStack that stores a string. Then the find() method is attached with the hayStack variable to search the ‘is’ string. There is also another variable indexPosition that stores the response of the find() method.

In the output of the above example we got 5. Because the index position of “is” is 5 in the string.

Example 2:

In previous example we searched the substring that was existing in the string. In this example let’s find the substring that doesn’t exist.

Look at below code, in which we have same string that we used for first example. In this example we passed a substring “not” that doesn’t exist in the string. That’s why the find() method returned -1 in the output.

hayStack = "Time is Money"
indexPosition = hayStack.find("not")
print(indexPosition)
# Output: -1


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Python, String,