Added function to get nth occurrence of a string in another string.
This commit is contained in:
parent
727c7bfd5c
commit
6161c081b1
1 changed files with 24 additions and 0 deletions
24
text.py
24
text.py
|
@ -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()
|
||||||
|
|
Loading…
Reference in a new issue