How to Use the find() Function in Python?

In this tutorial, I will explain how to use the find() function in Python. As a Python developer, I often came across a scenario where I needed to use the find() method. We will explore the find() method for strings and show you how to use it for various use cases.

find() Method in Python

The find method in Python is a built-in string method that returns the lowest index of the substring if it is found in a given string. If the substring is not found, it returns -1. This method is case-sensitive, meaning it differentiates between uppercase and lowercase characters.

Syntax

str.find(sub[, start[, end]])
  • sub: The substring you are searching for.
  • start: (Optional) The starting index where the search begins.
  • end: (Optional) The ending index where the search ends.

Read How to Use Single and Double Quotes in Python?

Examples

Let’s go through some practical examples to understand how the find method works. We’ll use USA-specific names and scenarios to make the examples more relatable.

Example 1: Find a Substring in a String

Suppose you have a string containing the names of some popular cities in the USA, and you want to find the position of the city “Chicago”.

cities = "New York, Los Angeles, Chicago, Houston, Phoenix"
position = cities.find("Chicago")
print(f"The position of 'Chicago' is: {position}")

Output:

The position of 'Chicago' is: 23

I have executed the above example code and added the screenshot below.

find() Function in Python

In this example, the find method searches for the substring “Chicago” and returns the index position 23.

Check out Python 3 vs Python 2 [Key Differences]

Example 2: Case Sensitivity

Let’s see what happens when we search for a substring with a different case.

cities = "New York, Los Angeles, Chicago, Houston, Phoenix"
position = cities.find("chicago")
print(f"The position of 'chicago' is: {position}")

Output:

The position of 'chicago' is: -1

I have executed the above example code and added the screenshot below.

Use the find() Function in Python

Since the find() method is case-sensitive, it returns -1 because “chicago” (lowercase) does not match “Chicago” (uppercase).

Read Difference Between “is None” and “== None” in Python

Example 3: Use Start and End Parameters

You can also specify the start and end parameters to limit the search within a specific range of the string.

cities = "New York, Los Angeles, Chicago, Houston, Phoenix"
position = cities.find("Houston", 30)
print(f"The position of 'Houston' starting from index 30 is: {position}")

Output:

The position of 'Houston' starting from index 30 is: 32

I have executed the above example code and added the screenshot below.

How to Use the find() Function in Python

Here, the search for “Houston” starts from index 30 , and the method returns the correct index 32.

Check out How to Comment Out a Block of Code in Python?

Use Cases

Let us see some use cases of the find() method in Python.

1. Parse Data from a Text File

Imagine you are working with a text file containing information about various states in the USA, and you need to extract specific details.

data = """
State: California
Capital: Sacramento
Population: 39538223

State: Texas
Capital: Austin
Population: 29145505

State: Florida
Capital: Tallahassee
Population: 21538187
"""

# Find the position of the state "Texas"
start_pos = data.find("State: Texas")
end_pos = data.find("State:", start_pos + 1)
texas_info = data[start_pos:end_pos].strip()
print(texas_info)

Output:

State: Texas
Capital: Austin
Population: 29145505

In this example, we locate the information for “Texas” by finding the starting and ending positions of the relevant text block.

Read Difference Between {} and [] in Python

2. Validate User Input

Suppose you are developing a web application where users can enter their email addresses, and you want to ensure that the email contains a specific domain.

email = "john.doe@example.com"
domain = "example.com"
if email.find(domain) != -1:
    print("The email contains the required domain.")
else:
    print("The email does not contain the required domain.")

Output:

The email contains the required domain.

This simple validation checks if the email address includes “example.com”.

Check out Compare Lists, Tuples, Sets, and Dictionaries in Python

3. Web Scraping

When scraping websites, you often need to find specific elements or text within the HTML content. The find method can help you locate these elements.

html_content = """
<html>
<head><title>Sample Website</title></head>
<body>
<p>Welcome to the Sample Website. This site is for demonstration purposes.</p>
<p>Contact us at contact@samplewebsite.com</p>
</body>
</html>
"""

# Find the position of the contact email
start_pos = html_content.find("contact@samplewebsite.com")
if start_pos != -1:
    print("Contact email found in the HTML content.")
else:
    print("Contact email not found.")

Output:

Contact email found in the HTML content.

This example demonstrates how you can locate specific text within HTML content.

Read Is Python an Object-Oriented Language?

Common Issues and How to Avoid Them

Let us see some common issues and how to avoid them.

1. Case Sensitivity

As mentioned earlier, the find method is case-sensitive. To perform a case-insensitive search, you can convert both the string and the substring to lowercase (or uppercase) before using the find method.

cities = "New York, Los Angeles, Chicago, Houston, Phoenix"
position = cities.lower().find("chicago".lower())
print(f"The position of 'chicago' is: {position}")

Output:

The position of 'chicago' is: 24

2. Handle Substrings Not Found

If the substring is not found, the find method returns -1. Always check for this condition to avoid unexpected results.

cities = "New York, Los Angeles, Chicago, Houston, Phoenix"
position = cities.find("Miami")
if position == -1:
    print("The city 'Miami' is not in the list.")
else:
    print(f"The position of 'Miami' is: {position}")

Output:

The city 'Miami' is not in the list.

Check out JavaScript vs Python for Web Development: Choosing the Right for Your Project

Conclusion

In this tutorial, I explained how to use the find() function in Python. I discussed find() function with syntax and examples to find a substring in a string, case sensitivity, use start and end parameters. We also discussed use cases and common issues and how to avoid them.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.