How to use Python find() | Python find() String Method

As programmers, we always look for shortcuts for common queries like finding the first element of the string, finding substrings of a string, finding the index of a string in a list, find all the occurrences of a character in a string, and many such common yet useful things. So, in this article, we will know how to find things in python. 

In python, we have find() function to perform some of the above operations in a string. We can use it to find a particular word or a specific character. So, let us first learn about find() function in python.   

Dissecting Find() in Python 

string.find(sub[, start[, end]]) 

Parameters– There are three parameters- sub, start, and end. Sub is the substring. Start and end are optional. They specify the starting and ending range of string to be searched.

Return Type– find() returns an integer type value.

find() returns the lowest index in a string where a substring sub is found. We can also give a range using start and end parameters, which are completely optional. The best thing about find() is that if that Substring is not there, it does not give an error (which index() do), and instead, it returns –1.  

Some common python programs using find()

Finding a particular character 

string=input("Enter a string:")
sub=input("Enter the character, you want to find:")
loc=string.find(sub)
print("First occurence of {} is at location:{}".format(sub,loc))
python find

Here, we have given a string- “we are learning python” and substring – ‘e’ which if we look is just after ‘w’, i.e. at index-1.

Enter a string:hello, we are learning python 
Enter the character, you want to find:e 
First occurence of e is at location:1

Finding a specific character in a range 

string=input("Enter a string:")
sub=input("Enter the character, you want to find:")
# Will start looking for the substring from index=5
start=5
# will look upto last index
end=-1
loc=string.find(sub,start,end)
print("Occurence of {} is at location:{}".format(sub,loc))
Enter a string:My name is Ashwini Mandani
Enter the character, you want to find:M
Occurence of M is at location:19

Here, we are trying to find the character ‘M’ between index -(5,last)

The first occurrence of a substring in a string 

string=input("Enter a string:")
sub=input("Enter the word, you want to find:")
loc=string.find(sub)
print("Occurence of {} is at location:{}".format(sub,loc))

Just like we did for character, we can also find a whole word in a string.

Enter a string:Can you can a can as a canner can can a can?
Enter the word, you want to find:can
Occurence of can is at location:8

How to find the first occurrence of a string from the last 

string=input("Enter a string:")
sub=input("Enter the word, you want to find:")
# rfind() is used to search for substring from the last
loc=string.rfind(sub)
print("Occurrence of {} is at location:{}".format(sub,loc))

rfind() is a built-in function in python which is used for finding the index of the substring from the last.

Enter a string:Can you can a can as a canner can can a can?
Enter the word, you want to find:can
Occurence of can is at location:40

What if Substring is not found in the string 

string=input("Enter a string:")
sub=input("Enter the word, you want to find:")
loc=string.find(sub)
# if substring is not there find() returns -1
if loc!=-1:
    print("Occurence of {} is at location:{}".format(sub,loc))
else:
    print("Substring not found","loc=",-1)
Enter a string:Python is the best
Enter the word, you want to find:java
Substring not found loc= -1

Unlike index(), find() returns -1 of the substring is not found in the string and because java is not in the string, it returns -1.

Please note that space is also counted in the index,

Some More Examples 

To find all the occurrences of a substring in a string. 

For this, we need to use finditer() of regular expressions. We will iterate over the string and wherever the substring is, it will return the span of the substring.

import re
# iterating through the string 
for sub in re.finditer('can', 'Can you can a can as a canner can can a can?'):
    # printing the span from where to where the substring occurred in the string 
    print(sub.span())

To find an index of an element in the list  

list1=[100,32,21,31,43,12,324]
print(list1.index(12))
Output-
5

find() cannot be used for list type values. So, we have to use the index() and the parameter should be the value we want to look inside the list.

To find the index of all the occurrences of a string in a list. 

list1=['Can', 'you', 'can', 'a', 'can' ,'as', 'a','canner', 'can' ,'can' ,'a' ,'can?']
sub='can'
# looping through the list and checking if the substring matches the string #at a particular index or not
for i in range(len(list1)):
    if list1[i]==sub:
        print(i)
2
4
8
9 

Loop over the string and wherever the the subtstring is found, return the index.

How to find the index of the element in python numpy array

We cannot use index() to find the index of an element in a numpy array. If we try to use, it will give Attribute Error.

import numpy as np
arr=np.array([21,223,123,653,322,653])
# look for the index where array is 653
np.where(arr==653)
(array([3, 5], dtype=int64),)

Must Read:

Conclusion

We have gone through a lot of important stuff in this article. The programs discussed here are very common in big projects. We now know the python find() and its parameter. We can also use index() function, but it gives an error if the substring is not there in the string.

Try to run the programs on your side and let us know if you have any queries.

Happy Coding!

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments