[Python-ideas] New explicit methods to trim strings

David Mertz mertz at gnosis.cx
Sun Mar 31 12:17:44 EDT 2019

On Sun, Mar 31, 2019 at 12:09 PM MRAB <python at mrabarnett.plus.com> wrote:

> > That said, I really like Brandt's ideas of expanding the signature of
> > .lstrip/.rstrip instead.
> >
> > mystring.rstrip("abcd") # remove any of these single character suffixes
> It removes _all_ of the single character suffixes.
> > mystring.rstrip(('foo', 'bar', 'baz')) # remove any of these suffixes
> In keeping with the current behaviour, it would strip _all_ of these
> suffixes.

Yes, the exact behavior would need to be documented.  The existing case
indeed removes *ALL* of the single letter suffixes.  Clearly that behavior
cannot be changed (nor would I want to, that behavior is useful).

It's a decision about whether passing a tuple of substrings would remove
all of them (perhaps repeatedly) or only one of them.  And if only one, is
it "longest wins" or "first wins."  As I say, any choice of the semantics
would be fine with me if it were documented... since this edge case will be
uncommon in most uses (certainly in almost all of my uses).


    basename = fname.rstrip(('.jpg', '.png', 'gif'))

This is rarely ambiguous, and does something concretely useful that I've
coded many times.  But what if:

    fname = 'silly.jpg.png.gif.png.jpg.gif.jpg'

I'm honestly not sure what behavior would be useful most often for this
oddball case.  For the suffixes, I think "remove them all" is probably the
best; that is consistent with thinking of the string passed in the existing
signature of .rstrip() as an iterable of characters.

But even if the decision was made to "only remove the single thing at end",
I'd still find the enhancement useful.  Sure, once in a while someone might
trip over the choice of semantics in this edge case, but if it were
documented, no big deal.

Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190331/72f74d3b/attachment.html>

More information about the Python-ideas mailing list