On 07Mar2020 15:31, Alex Hall <alex.moj...@gmail.com> wrote:
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
My utility library has them too, like this:
def cutprefix(s, prefix):
''' Strip a `prefix` from the front of `s`.
Return the suffix if `.startswith(prefix)`, else `s`.
Example:
>>> abc_def = 'abc.def'
>>> cutprefix(abc_def, 'abc.')
'def'
>>> cutprefix(abc_def, 'zzz.')
'abc.def'
>>> cutprefix(abc_def, '.zzz') is abc_def
True
'''
if prefix and s.startswith(prefix):
return s[len(prefix):]
return s
def cutsuffix(s, suffix):
''' Strip a `suffix` from the end of `s`.
Return the prefix if `.endswith(suffix)`, else `s`.
Example:
>>> abc_def = 'abc.def'
>>> cutsuffix(abc_def, '.def')
'abc'
>>> cutsuffix(abc_def, '.zzz')
'abc.def'
>>> cutsuffix(abc_def, '.zzz') is abc_def
True
'''
if suffix and s.endswith(suffix):
return s[:-len(suffix)]
return s
Like yours, they return the original object if unchanged. I think yours
misbehaved if given an empty suffix, which mine special cases out:
>>> 'abc'[:-0]
''
Cheers,
Cameron Simpson <c...@cskk.id.au>
_______________________________________________
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/COCNDNFGHLXDEPUMIR4ADIU3LBZY4L4H/
Code of Conduct: http://python.org/psf/codeofconduct/