diff options
Diffstat (limited to 'string_utils.py')
| -rw-r--r-- | string_utils.py | 14 |
1 files changed, 14 insertions, 0 deletions
diff --git a/string_utils.py b/string_utils.py index c995070..a766ada 100644 --- a/string_utils.py +++ b/string_utils.py @@ -1680,6 +1680,20 @@ def replace_all(in_str: str, replace_set: str, replacement: str) -> str: return in_str +def replace_nth(string: str, source: str, target: str, nth: int): + """Replaces the nth occurrance of a substring within a string. + + >>> replace_nth('this is a test', ' ', '-', 3) + 'this is a-test' + + """ + where = [m.start() for m in re.finditer(source, string)][nth - 1] + before = string[:where] + after = string[where:] + after = after.replace(source, target, 1) + return before + after + + if __name__ == '__main__': import doctest |
