Home  >  Article  >  Backend Development  >  How to Find the Nth Occurrence of a String in Python?

How to Find the Nth Occurrence of a String in Python?

DDD
DDDOriginal
2024-10-20 07:30:29634browse

How to Find the Nth Occurrence of a String in Python?

Finding the Nth Occurrence of a String in Python

Identifying the index of the n'th occurrence of a substring within a string is a common task in programming. However, Python's built-in find method doesn't provide a straightforward way to specify the occurrence number.

Solution:

Instead of relying on the find method directly, here's a Pythonic solution that iteratively locates the substring and increments the occurrence count until it reaches the desired value:

<code class="python">def find_nth(haystack: str, needle: str, n: int) -> int:
    """Find the index of the nth occurrence of needle in haystack."""
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+len(needle))
        n -= 1
    return start</code>

Usage:

To find the index of the second occurrence of the substring "foofoo" in the string "foofoofoofoo", you would call:

<code class="python">find_nth("foofoofoofoo", "foofoo", 2)</code>

This would return the index 6, corresponding to the starting position of the second "foofoo" substring.

Considerations for Overlapping Occurrences:

If you need to find the index of the n'th overlapping occurrence of the substring, you can modify the find_nth function to increment the starting position by 1 instead of the length of the needle:

<code class="python">def find_nth_overlapping(haystack, needle, n):
    """Find the index of the nth overlapping occurrence of needle in haystack."""
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+1)
        n -= 1
    return start</code>

The above is the detailed content of How to Find the Nth Occurrence of a String in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn