[Python-ideas] New explicit methods to trim strings

Chris Angelico rosuav at gmail.com
Sun Mar 31 05:03:11 EDT 2019

On Sun, Mar 31, 2019 at 7:36 PM Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, Mar 31, 2019 at 04:48:36PM +1100, Chris Angelico wrote:
> > Regardless of the method name, IMO the functions should accept a tuple
> > of test strings, as startswith/endwith do. That's a feature that can't
> > easily be spelled in a one-liner. (Though stacked suffixes shouldn't
> > all be removed - "asdf.jpg.png".cutsuffix((".jpg", ".png")) should
> > return "asdf.jpg", not "asdf".)
> There's a slight problem with that: what happens if more than one suffix
> matches? E.g. given:
>     "musical".lcut(('al', 'ical'))
> should the suffix "al" be removed, leaving "music"? (First match wins.)
> Or should the suffix "ical" be removed, leaving "mus"? (Longest match
> wins.)
> I don't think we can decide which is better, and I'm not keen on a
> keyword argument to choose one or the other, so I suggest we stick to
> the 90% solution of only supporting a single suffix.
> We can always revisit that in the future.

The only way there could be multiple independent matches is if one is
a strict suffix of another (as in your example here). In most cases,
this will require semantics at the control of the programmer, so I
would say "first match wins" is the only sane definition (as it
permits the programmer to order the cuttables to define the desired
semantics). The overwhelming majority of use cases won't be affected
by this decision, so first-wins won't hurt them.


More information about the Python-ideas mailing list