首頁  >  文章  >  後端開發  >  如何在Python中尋找子字串第N次出現?

如何在Python中尋找子字串第N次出現?

Barbara Streisand
Barbara Streisand原創
2024-10-20 07:29:02771瀏覽

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

在Python中尋找子字串的第n次出現

尋找字串中子字串的第n次出現可以透過以下各種方法來實作Python。一種簡單的方法是迭代方法,其中找到子字串的第一次出現,並透過在前一次出現的末尾之後增量搜尋來找到後續出現的位置。

要實現這種迭代方法,可以使用以下程式碼使用:

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

此函數採用 haystack 字串、needle 子字串和第 n 次出現來查找。它傳回與該事件相對應的索引,如果找不到該事件,則傳回 -1。

這種方法相對簡單,並且可以清楚地了解第 n 個事件的位置。但是,如果第 n 個出現位置距離字串開頭很遠,則可能需要多次遍歷字串。

例如,要查找字串“foofoofoofoo”中第二次出現的“foofoo”,可以使用以下程式碼:

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

這將傳回索引6,它對應於字串中第二次出現的「foofoo」。

以上是如何在Python中尋找子字串第N次出現?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn