I've defined functions like this in my own utility library and I use them
all the time, so I think they're very useful and would like to seem them
built in. But I have two functions for each end:

def strip_optional_suffix(string, suffix):
    """
    >>> strip_optional_suffix('abcdef', 'def')
    'abc'
    >>> strip_optional_suffix('abcdef', '123')
    'abcdef'
    """
    if string.endswith(suffix):
        return string[:-len(suffix)]
    return string


def strip_required_suffix(string, suffix):
    """
    >>> strip_required_suffix('abcdef', 'def')
    'abc'
    >>> strip_required_suffix('abcdef', '123')
    Traceback (most recent call last):
    ...
    AssertionError: String ends with 'def', not '123'
    """
    if string.endswith(suffix):
        return string[:-len(suffix)]
    raise AssertionError('String ends with %r, not %r' %
(string[-len(suffix):], suffix))

And I know that I use the required versions much more often, because
usually if the suffix isn't there that indicates a bug somewhere that I
need to know about. So I'd like to have both the optional and required
versions implemented in this proposal, and if that's too much to add then
just the required versions. But I suspect most people will be against the
idea.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/DHSLWA24ZLZU42GALCOTTCN33HQOIAXR/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to