First page Back Continue Last page Overview Graphics

Exercise

Write a function which calculates the position of

the n-th occurence of a

string sub in another string s.

If sub doesn't occur in s, -1 shall be returned.

def findnth(s, sub, n):

num = 0

start = -1

while num < n:

start = s.find(sub, start+1)

if start == -1: return -1

num += 1

return start

s = "abcxyzabcjkjkjkabclkjkjlkjabcjlj"

print(findnth(s,"abc", 4))