From 6161c081b161caf1716c0bb005a13f2cdd14d57a Mon Sep 17 00:00:00 2001 From: EKNr1 Date: Sun, 24 Mar 2024 18:42:43 +0100 Subject: [PATCH] Added function to get nth occurrence of a string in another string. --- text.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) 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()