From 1ee64f3522abbbc2df154c8f44be87929a16e17e Mon Sep 17 00:00:00 2001 From: Scott Gasch Date: Wed, 23 Feb 2022 09:32:42 -0800 Subject: Added a box method and fixed the broken justify method. --- string_utils.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'string_utils.py') 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 -- cgit v1.3