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

DDD
發布: 2024-10-20 07:30:29
原創
626 人瀏覽過

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

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

辨識字串中第n 次出現的子字串的索引是程式設計中的常見任務。然而,Python 內建的 find 方法並沒有提供直接的方法來指定出現次數。

解決方案:

而不是直接依賴find 方法,這是一個Pythonic 解決方案,它迭代地定位子字串並增加出現次數,直到達到所需值:

<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>
登入後複製

用法:

尋找在字串“foofoofoofoo”中第二次出現子字串“foofoo”,您可以呼叫:

<code class="python">find_nth("foofoofoofoo", "foofoo", 2)</code>
登入後複製

這將傳回索引6,對應於第二個「foofoo」子字串的起始位置。

重疊出現的注意事項:

如果需要查找子字串第n 個重疊出現的索引,可以修改find​​_nth 函數以增加起始位置以1 取代針的長度:

<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>
登入後複製

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

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!