Added function to get nth occurrence of a string in another string.

This commit is contained in:
The Wobbler 2024-03-24 18:42:43 +01:00
parent 727c7bfd5c
commit 6161c081b1

24
text.py
View file

@ -111,5 +111,29 @@ def rsap(old: str, replace: str, position: int):
return old[:position] + replace + old[position + 1:] 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__": if __name__ == "__main__":
example() example()