There isn't a builtin for this, but you can easily write a function:
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)
In use:
>>> 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
(Note that 'a'
actually occurs at index 8, not 7, in the first case.)
Note: In the second s.index
call, I'm setting the end
parameter in order to avoid searching parts of the string that have already been searched. This is a bit of a premature optimization, but it's also a bit of a clarification about exactly which parts of the string are being searched in each step. The +len(sub)-1
is to allow for multi-character sub
that spans index n
, like:
>>> index_circular('abc', 'ab', 1)
0