Skip to content

Commit

Permalink
add strict option to strip prefix/suffix, which can be used to ensure…
Browse files Browse the repository at this point in the history
… the stripped substring was present
  • Loading branch information
wimglenn committed Oct 9, 2018
1 parent 016157b commit 3b054b9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
10 changes: 10 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ def test_strip_suffix(in_, suf, out):
assert strip_suffix(in_, suf) == out


def test_strip_prefix_strict():
with pytest.raises(WimpyError, match="string doesn't start with prefix"):
strip_prefix("www.yahoo.com", "ww.", strict=True)


def test_strip_suffix_strict():
with pytest.raises(WimpyError, match="string doesn't end with suffix"):
strip_suffix("www.yahoo.com", ".org", strict=True)


def test_working_directory(tmpdir):
before = os.getcwd()
with working_directory(tmpdir):
Expand Down
14 changes: 10 additions & 4 deletions wimpy/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,23 @@ def working_directory(path):
os.chdir(prev_dir)


def strip_prefix(s, prefix):
"""Removes the prefix, if it's there, otherwise returns input string unchanged"""
def strip_prefix(s, prefix, strict=False):
"""Removes the prefix, if it's there, otherwise returns input string unchanged.
If strict is True, also ensures the prefix was present"""
if s.startswith(prefix):
return s[len(prefix) :]
elif strict:
raise WimpyError("string doesn't start with prefix")
return s


def strip_suffix(s, suffix):
"""Removes the suffix, if it's there, otherwise returns input string unchanged"""
def strip_suffix(s, suffix, strict=False):
"""Removes the suffix, if it's there, otherwise returns input string unchanged.
If strict is True, also ensures the suffix was present"""
if s.endswith(suffix):
return s[: len(s) - len(suffix)]
elif strict:
raise WimpyError("string doesn't end with suffix")
return s


Expand Down

0 comments on commit 3b054b9

Please sign in to comment.