首页  >  文章  >  后端开发  >  如何在Python中查找字符串第N次出现?

如何在Python中查找字符串第N次出现?

DDD
DDD原创
2024-10-20 07:30:29634浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn