If the prefix/suffix does not match the beginning or the end of a string, then, depending on how I call these functions, they should either raise an exception or return the original text unmodified.
I am using these inside of a simple script for now, so there was no need to make these member functions of some class. I am hoping to find a way to simplify the logic, extract any common code into private function(s), improve the code style (although I think there are several different standards).
def remove_prefix(text, prefix, raise_if_no_match=True):
exc_msg = 'Text "{}" does not start with a prefix "{}".'.format(text, prefix)
if not prefix or not text:
if not raise_if_no_match:
return text
if len(prefix) == len(text):
return ''
raise ValueError(exc_msg)
if text.startswith(prefix):
return text[len(prefix):]
if raise_if_no_match:
raise ValueError(exc_msg)
return text
def remove_suffix(text, suffix, raise_if_no_match=True):
exc_msg = 'Text "{}" does not end with a suffix "{}".'.format(text, suffix)
if not suffix or not text:
if not raise_if_no_match:
return text
if len(suffix) == len(text):
return ''
raise ValueError(exc_msg)
if text.endswith(suffix):
return text[:-len(suffix):]
if raise_if_no_match:
raise ValueError(exc_msg)
return text
print remove_prefix('Hello, World', 'Hello, ')
# ValueError: Text "Hello, World" does not start with a prefix "Hello, Hello".
#print remove_prefix('Hello, World', 'Hello, Hello')
print remove_prefix('Hello, World', 'Hello, Hello', raise_if_no_match=False)
print remove_suffix('I am singing in the rain', ' in the rain')
# ValueError: Text "I am singing in the rain" does not end with a suffix "swinging in the rain".
#print remove_suffix('I am singing in the rain', 'swinging in the rain')
print remove_suffix('I am singing in the rain', 'swinging in the rain', raise_if_no_match=False)
Output:
World Hello, World I am singing I am singing in the rain
ifto firstraise. The rest is ok. \$\endgroup\$