ホームページ  >  記事  >  バックエンド開発  >  Python で文字列の N 番目の出現を見つける方法?

Python で文字列の N 番目の出現を見つける方法?

DDD
DDDオリジナル
2024-10-20 07:30:29626ブラウズ

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

Python での文字列の N 番目の出現の検索

文字列内の部分文字列の n 番目の出現のインデックスを識別するのは、プログラミングにおける一般的なタスク。ただし、Python の組み込みの find メソッドには、出現番号を指定する簡単な方法がありません。

解決策:

find メソッドに直接依存する代わりに、これは、部分文字列を繰り返し見つけて、目的の値に達するまで出現回数を増やす Python ソリューションです。

<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" が 2 番目に出現した場合、次のように呼び出します。

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

これにより、2 番目の "foofoo" 部分文字列の開始位置に対応するインデックス 6 が返されます。

重複出現に関する考慮事項:

部分文字列の 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。