Separate box and print_box.
[python_utils.git] / string_utils.py
index c995070ff09fbe128d67d27d3ff42007e94ba2d5..a766adabe97ffc8432a9bda280c66107634bc52b 100644 (file)
@@ -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