From a3ef533e67420319965c2caad921b72b14adbef0 Mon Sep 17 00:00:00 2001 From: Matthew Andres Moreno Date: Sun, 5 Nov 2023 14:59:42 -0500 Subject: [PATCH] Implement, test splice --- conduitpylib/test/test_utils/test_splice.py | 29 ++++++++++++++++++ conduitpylib/utils/__init__.py | 2 ++ conduitpylib/utils/splice.py | 33 +++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 conduitpylib/test/test_utils/test_splice.py create mode 100644 conduitpylib/utils/splice.py diff --git a/conduitpylib/test/test_utils/test_splice.py b/conduitpylib/test/test_utils/test_splice.py new file mode 100644 index 000000000..e60eac89a --- /dev/null +++ b/conduitpylib/test/test_utils/test_splice.py @@ -0,0 +1,29 @@ +from conduitpylib.utils import splice + + +def test_splice_removal_only(): + assert splice("Hello world", (5, 11)) == "Hello" + + +def test_splice_insertion_only(): + assert splice("123456789", (3, 3), "ABC") == "123ABC456789" + + +def test_splice_removal_and_insertion(): + assert splice("Hello world", (0, 5), "Goodbye") == "Goodbye world" + + +def test_splice_empty_string(): + assert splice("", (0, 0), "Hello") == "Hello" + + +def test_splice_full_replacement(): + assert splice("Hi", (0, 2), "Hello") == "Hello" + + +def test_splice_out_of_bounds(): + assert splice("Hello", (0, 15)) == "" + + +def test_splice_negative_indices(): + splice("Hello", (-3, -1)) diff --git a/conduitpylib/utils/__init__.py b/conduitpylib/utils/__init__.py index 88003221c..0df1c3be5 100644 --- a/conduitpylib/utils/__init__.py +++ b/conduitpylib/utils/__init__.py @@ -14,6 +14,7 @@ seaborn_monkeypatched_kdecache, seaborn_unmonkeypatch_kdecache, ) +from .splice import splice from .strip_end import strip_end from .UnequalSentinel import UnequalSentinel @@ -30,6 +31,7 @@ 'seaborn_monkeypatch_kdecache', 'seaborn_monkeypatched_kdecache', 'seaborn_unmonkeypatch_kdecache', + 'splice', 'strip_end', 'UnequalSentinel', ] diff --git a/conduitpylib/utils/splice.py b/conduitpylib/utils/splice.py new file mode 100644 index 000000000..30be40eff --- /dev/null +++ b/conduitpylib/utils/splice.py @@ -0,0 +1,33 @@ +import typing + + +def splice(string: str, span: typing.Tuple[int, int], insert: str = "") -> str: + """Remove index span from string and optionally insert new content. + + Parameters + ---------- + string : str + The original string to be spliced. + span : tuple[int, int] + A tuple indicating the start and end indices for the splice operation. + + The start index is inclusive and the end index is exclusive. + insert : str, default "" + The string to be inserted in place of the removed span. + + Defaults to an empty string, i.e., simple removal. + + Returns + ------- + str + The spliced string after removal and insert operation. + + Examples + -------- + >>> splice("Hello world", (1, 6)) + 'Hworld' + >>> splice("Hello world", (0, 5), "Goodbye") + 'Goodbye world' + """ + start, end = span + return string[:start] + insert + string[end:]