以循环方式查找特定字符索引的Pythonic方法

use*_*192 5 python

假设我有一个像这样的字符串:

'abcdefgha'
Run Code Online (Sandbox Code Playgroud)

我想找到a索引 2 之后的下一个字符的索引(以循环方式)。这意味着在这种情况下它应该找到索引 7(通过mystr.index('a', 2));然而,在这种情况下:

'abcdefgh'
Run Code Online (Sandbox Code Playgroud)

它应该返回索引 0。有没有这样的内置函数?

wja*_*rea 5

没有为此的内置函数,但您可以轻松编写一个函数:

def index_circular(s: str, sub: str, n: int) -> int:
    try:
        # Search starting from n
        return s.index(sub, n)
    except ValueError:
        # Wrap around and search from the start, until n
        return s.index(sub, 0, n+len(sub)-1)
Run Code Online (Sandbox Code Playgroud)

正在使用:

>>> n = 2
>>> c = 'a'
>>> index_circular('abcdefgha', c, n)
8
>>> index_circular('abcdefgh', c, n)
0
>>> index_circular('bcdefgh', c, n)
Traceback (most recent call last):
    ...
ValueError: substring not found
Run Code Online (Sandbox Code Playgroud)

(请注意,'a'在第一种情况下,实际上发生在索引 8 处,而不是 7 处。)

注意:在第二次s.index调用中,我设置end参数是为了避免搜索已搜索过的字符串部分。这有点不成熟的优化,但它也澄清了每个步骤中到底搜索字符串的哪些部分。这+len(sub)-1是为了允许sub跨索引的多字符n,例如:

>>> index_circular('abc', 'ab', 1)
0
Run Code Online (Sandbox Code Playgroud)