Removing all but one instance of a phrase from a string

Oh, sorry. I missunderstood. I was guessing as you did not show how the function was called.

You haven’t specified what to do with spaces. Given s = “the cat the cat the cat” and phrase=“the cat”, should the output be "the cat " (with two trailing spaces) or “the cat” (without trailing spaces)? Or if s = “the cat on the mat” and phrase=“on”, should the output be “the cat the mat” (with two spaces after cat) or with only one space?

The following leaves spaces in place:

def delete_repeated_phrase(s, phrase):
    j = s.find(phrase)
    if j >= 0:
        k = j + len(phrase)
        s = s[:k] + s[k:].replace(phrase, "")
    return s

Thanks. Ideally it’d be optional to remove trailing spaces by passing a boolean as a 3rd optional parameter.

The function you’ve coded removes all instances of the phrase from s, whereas the first instance should be left intact.

No, it leaves the first found instance intact. Give it a try.

If a prefix of phrase is also a sufix, it is possible that the second occurrence of the phrase doesn’t get removed.

For example,

>>> delete_repeated_phrase('aaa', 'aa')
'aaa'

Maybe that is not a requirement. I don’t know whether they want to return 'aaa' or 'aa' in that case.
From a message above, it does look like they don’t want to get 'a'.

Apologies, I shouldn’t do things late at night, I clearly wasn’t seeing straight