First page Back Continue Last page Overview Graphics

Exercise

Write a function which replaces the n-th occurence of a string sub by a string replacement.

The function shall return the changed string or the unchanged, or the original string, if replacement didn't occur in the string.

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

def replacenth(source, search, replacement, n):

pos = findnth(source, search, n)

if pos == -1: return source

return source[:pos] + replacement + source[pos+len(search):]

s = "abcxyzabcjkjkjkabclkjkjlkjabcjlj"

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

print(replacenth(s,"abc","---", 4))