summaryrefslogtreecommitdiff
path: root/string_utils.py
diff options
context:
space:
mode:
authorScott Gasch <[email protected]>2022-02-23 09:32:42 -0800
committerScott Gasch <[email protected]>2022-02-23 09:32:42 -0800
commit1ee64f3522abbbc2df154c8f44be87929a16e17e (patch)
tree98062124eb9916afcaa2ae1463f6f9f114fa36ae /string_utils.py
parentd1f18fdf430eee4292938dd18b922d6d6e05e18c (diff)
Added a box method and fixed the broken justify method.
Diffstat (limited to 'string_utils.py')
-rw-r--r--string_utils.py14
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