How to Find the Second Occurrence of a Substring in a Python String?

As a Python developer working on a text analysis project for a publishing company in Chicago, I came across a scenario where I needed to identify the second occurrence of specific keywords within articles. After researching and testing different methods, I found several effective solutions. In this tutorial, I will explain how to find the second occurrence of a substring in a Python string with examples.

Find the Second Occurrence of a Substring in a Python String

Let’s say you have a string that represents a list of American cities, separated by commas:

cities = "New York, Los Angeles, Chicago, Houston, New York, Philadelphia"

Your task is to find the index of the second occurrence of “New York” in this string.

Read How to Convert a String to Date in Python?

Method 1: Use the find() Function

Python’s built-in find() function can locate the first occurrence of a substring within a string. To find the second occurrence, we can use find() twice.

Here’s how it works:

cities = "New York, Los Angeles, Chicago, Houston, New York, Philadelphia"
first_occurrence = cities.find("New York")
second_occurrence = cities.find("New York", first_occurrence + 1)

if second_occurrence != -1:
    print(f"The second occurrence of 'New York' is at index {second_occurrence}")
else:
    print("'New York' does not occur twice in the string")

Output:

The second occurrence of 'New York' is at index 41

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

Find the Second Occurrence of a Substring in a Python String

In this code:

  1. We use find() to locate the first occurrence of “New York” and store its index in first_occurrence.
  2. We call find() again, but this time we start searching from first_occurrence + 1. This ensures we find the next occurrence after the first one.
  3. If second_occurrence is not -1 (which indicates the substring was not found), we print its index. Otherwise, we print a message indicating there is no second occurrence.

Check out How to Print Strings and Integers Together in Python?

Method 2: Use a Custom Function

We can also create a reusable function to find the nth occurrence of a substring. This is helpful if you need to find occurrences beyond just the second one.

def find_nth_occurrence(string, substring, n):
    occurrences = 0
    index = -1

    while occurrences < n:
        index = string.find(substring, index + 1)
        if index == -1:
            break
        occurrences += 1

    return index

cities = "New York, Los Angeles, Chicago, Houston, New York, Philadelphia"
second_new_york = find_nth_occurrence(cities, "New York", 2)

if second_new_york != -1:
    print(f"The second occurrence of 'New York' is at index {second_new_york}")
else:
    print("'New York' does not occur twice in the string")

Output:

The second occurrence of 'New York' is at index 41

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

How to Find the Second Occurrence of a Substring in a Python String

In this custom find_nth_occurrence() function:

  1. We initialize occurrences to keep track of how many times we’ve found the substring, and index to store the current index.
  2. We start a loop that continues until we’ve found the nth occurrence (or run out of occurrences).
  3. Inside the loop, we use find() to locate the next occurrence, starting from the previous index + 1.
  4. If find() returns -1, we break the loop since there are no more occurrences.
  5. Otherwise, we increment occurrences and continue the loop.
  6. Finally, we return the index of the nth occurrence (or -1 if not found).

Read How to Truncate a String to a Specific Length in Python?

Handle Edge Cases

When searching for occurrences, it’s important to consider edge cases. For example:

  • What if the substring doesn’t occur at all?
  • What if the substring occurs only once?
  • What if the substring is empty?

Here’s an example that demonstrates handling these cases:

def find_second_occurrence(string, substring):
    if not substring:
        return "Substring cannot be empty"

    first_occurrence = string.find(substring)
    if first_occurrence == -1:
        return "Substring not found"

    second_occurrence = string.find(substring, first_occurrence + 1)
    if second_occurrence == -1:
        return "Substring occurs only once"

    return second_occurrence

print(find_second_occurrence("John Smith, Jane Doe, John Doe", "John"))
print(find_second_occurrence("John Smith, Jane Doe, John Doe", "Doe"))
print(find_second_occurrence("John Smith, Jane Doe, John Doe", "Mike")) 
print(find_second_occurrence("John Smith, Jane Doe, John Doe", ""))

Output:

22
27
Substring not found
Substring cannot be empty

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

Find the Second Occurrence of a Substring in a Python String handle case

By adding these checks, we ensure our function provides informative feedback for different scenarios.

Check out How to Get the Last 4 Characters of a String in Python?

Conclusion

In this tutorial, I have explained how to find the second occurrence of a substring in a Python string. I covered some important methods like using the find() function and using the custom function. I also covered how to handle edge cases.

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.