Cover Image for Python | Ways to find nth Occurrence of Substring in a String
221 views

Python | Ways to find nth Occurrence of Substring in a String

You can find the nth occurrence of a substring in a string in Python using various approaches, depending on your requirements and the complexity of the problem. Here are a few methods to achieve this:

Method 1: Using a Loop

Python
def find_nth_occurrence(input_string, substring, n):
    start = input_string.find(substring)
    while start >= 0 and n > 1:
        start = input_string.find(substring, start + 1)
        n -= 1
    return start

input_string = "Python is a powerful programming language. Python is easy to learn."
substring = "Python"
n = 2
result = find_nth_occurrence(input_string, substring, n)
print(f"The {n}nd occurrence of '{substring}' starts at index {result}")

Method 2: Using Regular Expressions

Python
import re

def find_nth_occurrence(input_string, substring, n):
    pattern = re.compile(f"((?:.*?{re.escape(substring)}){{{n - 1}}}(.*?{re.escape(substring)}))")
    match = pattern.search(input_string)
    if match:
        return match.start(2)
    else:
        return -1

input_string = "Python is a powerful programming language. Python is easy to learn."
substring = "Python"
n = 2
result = find_nth_occurrence(input_string, substring, n)
print(f"The {n}nd occurrence of '{substring}' starts at index {result}")

Method 3: Using str.split()

Python
def find_nth_occurrence(input_string, substring, n):
    parts = input_string.split(substring, n)
    if len(parts) < n:
        return -1
    return len(input_string) - len(parts[-1]) - len(substring)

input_string = "Python is a powerful programming language. Python is easy to learn."
substring = "Python"
n = 2
result = find_nth_occurrence(input_string, substring, n)
print(f"The {n}nd occurrence of '{substring}' starts at index {result}")

Method 4: Using a List Comprehension (Advanced)

Python
def find_nth_occurrence(input_string, substring, n):
    indices = [i for i, c in enumerate(input_string) if input_string[i:i + len(substring)] == substring]
    if len(indices) >= n:
        return indices[n - 1]
    return -1

input_string = "Python is a powerful programming language. Python is easy to learn."
substring = "Python"
n = 2
result = find_nth_occurrence(input_string, substring, n)
print(f"The {n}nd occurrence of '{substring}' starts at index {result}")

Choose the method that best suits your needs and coding style. Method 1 and Method 2 are straightforward and recommended for most use cases.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS