Search for Courses, Topics
certificate icon
Certificate

Learn on Scaler Topics and get certified.

static-certificate

Python String find() Method

Learn about find() Function in Python.

11 Oct 2021-7 mins read

Overview

find() is a Python library function that is used to find the index of the first occurrence of a substring from the given string. If find() is unable to locate the substring then it returns -1 instead of throwing an exception.

Before reading this article, understand the following Python programming topics:

Scope of the article

In this article you will learn about find(), rfind() and index(). You will learn how these functions work with the help of different examples in Python programming. You will also learn how to count all the occurrences of a substring by using a simple python loop.

Introduction

While creating software there are certain tasks that require us to search for some words/sentences, suppose you are making a text editor then one of the most important features is Find and Replace. For that, you have to search for words and even sentences in the document. In such scenarios find() function comes to the rescue.

find() function is a part of python library. find() takes a string as input. It is used to find the index of the first occurrence of the substring inside a given string. If the substring is not present then it returns -1 but it does not throw an exception.

Syntax of find() Function in Python

string.find(substring, start, end)
  • string is the original sentence/word in which you want to look for the substring.
  • substring is the sentence/word which you have to search.
  • start and end are optional parameters. They specify the range where the substring needs to be searched.

What Does find() Python Return?

  • If the substring exists in the string then it will return the index of the first occurrence of substring.
  • If the substring does not exist then it will return -1.

Here is an example,

paragraph = 'I am learning python and it is a great language'
print(paragraph.find('I'))
print(paragraph.find('q'))

Output:

0
1

In this code, we created a string variable names paragraph and we called find() on it to find the occurrence of "I" and "q". Here, "I" comes at the very start of the string so its index 0 is returned, but in the second case "q" is not found, so we get -1

Let's look at different types of examples

1) No start and End Arguments are Given

str = 'python is super easy to learn and work with'
print("found at: ", str.find('python'))
print(str.find('q'))

Output:

found at: 0
-1

Here we have create a variable str which contains a sentence and then we called find() on str and gave it 'python' as an argument. So, find() will search for 'python' in str and return the index of its first occurrence in str

When start and end arguments are not given then find() starts to look from the beginning and searches till the end of the string.

What if we use default arguments?

str = 'I learned very early the difference between knowing the name of something and knowing something.'
print("found at: ", str.find('difference'))

Output:

found at:25

If you do not pass start and end arguments then their default values are used. The default value of start is 0 and the end is length of the string.

2) Start and End arguments are Given

str = 'Study hard what interests you the most in the most undisciplined, irreverent and original manner possible.'
print("found at: ", str.find('interests', 10, 30))
print("found at: ", str.find('interests', 30, 40))

Output

found at: 16
found at: -1

Here, we have made a variable called str and have stored a sentence in it. Then we call find() on it and gave it 'interests', 10 and 30 as arguments. 10 tells find() that it has to start looking for the substring (i.e interests) from the 10th position and 30 tells find() to look till the 30th position and not beyond that.

So, start and end arguments set a range and find() searches for the substring only in that range.

'interests' comes at 16th position, which is between 10 and 30, so for the first print() the output is 16 and for the second it is -1 as 'interests' is not present between 30 and 40.

3) Only Start Argument is Given

str = 'Study hard what interests you the most in the most undisciplined, irreverent and original manner possible.'
print("found at: ", str.find('interests', 10))
print("found at: ", str.find('interests', 30))

Output:

found at: 16
found at: -1

Here again we have stored a sentence in a variable called str and we call find() on str and pass 'interests' and 10 as arguments. 10 here tells find() that it has to start looking from the 10th index and since there is no end argument so it will look till the end of the string.

When only start is given then the end takes the default value i.e. length of the string automatically. So, here we define the starting range but not the ending range.

'interests' comes at 16th position, so for the first print() the output is 16 and for the second it is -1 as 'interests' is not present after 16.

Can I find the position of a substring?

Yes you surely can.

str = 'I learned very early the difference between knowing the name of something and knowing something.'
print("found at: ", str.find('very early'))

Output:

10

In the find() you can pass a whole sentence as a input. Here we have passed 'very early' as input to find() and find() searchs for 'very early' in str and returns 10 as position of 'very early', which is the correct position.

Now What is rfind() in Python?

rfind() is similar to find() but there is a small difference. rfind() returns the highest index of the substring. Similar to find() it returns -1 if the substring is not found.

Its syntax is the same as find() and it also takes the arguments that find() takes.

Here is an example which will make things clear.

myStr = "py py py py"
print(myStr.find("py"))
print(myStr.rfind("py"))

Output:

0
9

Here we fist created a string variable named myStr and called find() and rfind() on it. find() returned 0 and rfind() returned 9.

This is because, rfind() returned the index of the last occurence of 'py' while find() returned the index of the first occurence of 'py'.

Python String index()

index() function is also a library function of Python. This function gives the poisition of the substring just like find() but the difference is index() will throw a ValueError if the substring is not present in the string. In such a case, find() returns -1.

myStr = "py py py py"
print(myStr.find("js"))
print(myStr.index("js"))

Output:

-1
Traceback (most recent call last):
  File "D:\Programming\python\article\find.py", line 38, in <module>
    print(myStr.index("js"))
ValueError: substring not found

Here you can see that find() returned -1 whereas index() threw an substring not found error.

How to Find Total Occurences of a Substring?

This is also a simple task, we can do this by using find() and a loop.

repeatingStr = 'This is a repeating string, repeating string, repeating string.'
start = 0
occurrences = 0
for i in range(len(repeatingStr)):
    j = repeatingStr.find('repeating', start)
    if(j != -1):
        start = j+1
        occurrences += 1

print("Total occurrences are: ", occurrences)

Output:

Total occurrences are:  3

In this code, first, we have set the value of start and occurrences to 0 and then we used a for loop to iterate over the string repeatingStr.

Inside the loop we call find() to check if the substring 'repeating' is inside repearingStr or not.

If it is present then we add 1 to the value of start and increase the value of occurrences by 1. The reason we add 1 to start is so that the substring is not counted twice.

When the loop is completed then the value of occurrences is printed.

Summary

  • find() returns the first occurrence of the substring in the given string. It will return -1 if the substring is not present.
  • find() can take 3 parameters: substring, start, end. The start and end are optional.
  • start and end are useful when you have to search for a substring at some specific position inside a string.
  • rfind() is similar to find() but it returns the last occurence of the substring. It also returns -1 if the substring is not present.
  • index() is also a similar function but it will throw a Value Error if the substring is not found.