Tìm occurrence thứ n của substring trong string bằng cách split tại substring với max n+1 splits. Nếu list kết quả size > n+1, nghĩa là substring xuất hiện > n lần. Index tìm bằng công thức: độ dài string gốc - độ dài phần split cuối - độ dài substring.
Ví dụ
def findnth(string, substring, n):
parts = string.split(substring, n + 1)
if len(parts) <= n + 1:
return -1
return len(string) - len(parts[-1]) - len(substring)
findnth('foobarfobar akfjfoobar afskjdf foobar', 'foobar', 2)
Output
31
n ở đây bắt đầu từ 0. Dễ dàng thay đổi nếu muốn bắt đầu từ 1.