diff --git a/text.py b/text.py index 3805ec4..4ca69fd 100644 --- a/text.py +++ b/text.py @@ -111,5 +111,29 @@ def rsap(old: str, replace: str, position: int): return old[:position] + replace + old[position + 1:] +def find_nth_occurrence(string: str, substring: str, n: int): + """ + Find the nth occurrence of a substring in a string. + :param int n: 0 is the first occurrence + :return: -1 when the substring was not found, 0 is the first character. + """ + + if len(substring) == 1: # make sure the replace string is not the substring (in rare cases, it might not work) + if substring == "a": + rep = "b" + + else: + rep = "a" + + else: + if not substring in "a" * len(substring): + rep = "a" * len(substring) + + else: + rep = "b" * len(substring) + + return string.replace(substring, rep, n - 1).find(substring) + + if __name__ == "__main__": example()