How to Use Find Method in Python

How to Use Find Method in Python

5 mins read131 Views Comment
Updated on Mar 31, 2023 16:55 IST

The find function in Python is a useful tool for searching through a string and finding the first occurrence of a specified substring. With just a few lines of code, you can quickly and easily locate a particular string within a larger text document. Learn more about how to use the find function in Python to streamline your text processing tasks and improve the efficiency of your code.

2023_03_MicrosoftTeams-image-246.jpg

In Python, the find() method is utilized to determine the initial position of a particular substring within a given string. It is commonly used to perform text processing and search operations in Python programs. 

In this article, we will discuss this function and understand its use with the help of examples. We will be covering the following sections:

Introduction to find() Method in Python

The find() method is a built-in function in Python that allows you to search for a substring within a string and return the index of the first occurrence of that substring. If the find() function is unable to locate the specified substring, it will return -1 instead of generating an exception. 

What is Programming What is Python
What is Data Science What is Machine Learning

Syntax of find()

The syntax of find() method in Python is given as:

 
string.find(substring, start, end)
Copy code

Parameters of find()

The find() method takes the following parameters:

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

Return Value of find()

If the substring exists in the string, the find() method will return the index of the first occurrence of the substring. If the substring does not exist, then it will return -1.

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

Examples of Using the find() Method in Python

Example 1: Checking if a substring is present in a string

 
string = "The quick brown fox jumps over the lazy dog"
substring = "brown"
if string.find(substring) != -1:
print("The substring is present in the string")
else:
print("The substring is not present in the string")
Copy code

Output

The substring is present in the string

In this example, we use the find() method to check if the substring “brown” is present in the string “The quick brown fox jumps over the lazy dog”. Since the find() method returns an index greater than or equal to 0 if the substring is present, we check if the returned value is not -1 to conclude that the substring is present in the string.

Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

Example 2: Searching for a file in a directory

 
import os
directory = "/home/user/documents"
filename = "report.docx"
for root, dirs, files in os.walk(directory):
if filename in files:
print("File found in:", root)
break
Copy code

Output

In this example, we use the os.walk() method to traverse a directory and its subdirectories and find a file with a specific name (in this case, “report.docx”). Inside the loop, we use the find() method to check if the filename is present in the files list. If it is present, we print the path of the directory where the file was found using root

Example 3: Counting the number of occurrences of a substring in a string

 
string = "The quick brown fox jumps over the lazy dog"
substring = "o"
count = 0
index = 0
while True:
index = string.find(substring, index)
if index == -1:
break
count += 1
index += 1
print("The substring '", substring, "' occurs", count, "times in the string")
Copy code

Output:

The substring ‘ o ‘ occurs 4 times in the string

In this example, we use the find() method to count the number of occurrences of the substring “o” in the string “The quick brown fox jumps over the lazy dog”. We start the search from index 0 and use a loop to increment the index each time we find a match until we have searched the entire string. We keep a count of the number of matches found in the count variable and print the result after the loop is complete. 

Example 4: Extracting a substring from a string

 
string = "The quick brown fox jumps over the lazy dog"
start_index = string.find("brown") + len("brown")
end_index = string.find(" jumps")
substring = string[start_index:end_index]
print(substring)
Copy code

Output:

“fox”

In this example, we use the find() method to find the index of the first non-whitespace character in the string and the rfind() method to find the index of the last non-whitespace character. We add 1 to the last index because slicing is exclusive to the end index. We then use the strip() method [insert link] to remove any leading or trailing whitespace from the selected substring.

What is rfind() in Python?

The rfind() is a method in Python that works similar to the find() method but searches for a substring from the end of a string instead of the beginning. The r in rfind() stands for “reverse”.

The syntax of rfind() is the same as find(), and it also takes the same arguments as find().

Here is an example of using rfind() to find the index of the last occurrence of a substring:

 
string = "hello world"
last_index = string.rfind("l")
print(last_index)
Copy code

Output:

9

In this example, the rfind() method searches for the last occurrence of the letter “l” in the string “hello world” and returns the index of the character at position 9, which is the second “l” in “world”.

Conclusion

In this article, we have briefly discussed all about find method in Python. The find() method is particularly useful when dealing with text data and when you need to locate specific patterns within strings.

Hope you will like the article.

Happy Learning!!

Contributed By: Prerna Singh

FAQs

What is the difference between find() and index()?

Both find() and index() are used to find the index of a substring in a string. However, the find() method returns -1 if the substring is not found, whereas index() raises a ValueError exception. So, if you are not sure whether the substring exists in the string or not, use find(). If you are sure the substring exists in the string, use index().

How does find() handle overlapping substrings?

If the substring you are searching for overlaps with itself, find() will return the index of the first occurrence of the substring. For example, if you search for "aaa" in the string "aaaa", find() will return 0.

Can find() search for multiple substrings at once?

No, find() can only search for one substring at a time. If you need to search for multiple substrings, you will need to call find() multiple times.

Does find() differentiate between uppercase and lowercase letters?

Yes, by default, find() is case-sensitive, so it will only find substrings that match the case of the search string. However, you can use the lower() or upper() methods to convert the search string and the string being searched to either all lowercase or all uppercase before calling find(), if you want to perform a case-insensitive search.

Can find() be used with non-string data types?

No, find() is a string method, so it can only be used with string data types. If you want to search for a substring in a non-string data type, you will need to convert it to a string first.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio