[Python-ideas] New explicit methods to trim strings

MRAB python at mrabarnett.plus.com
Sun Mar 31 13:31:47 EDT 2019


On 2019-03-31 17:17, David Mertz wrote:
> On Sun, Mar 31, 2019 at 12:09 PM MRAB <python at mrabarnett.plus.com 
> <mailto: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).
>
> E.g.
>
>     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.
>
Could/should we borrow from .replace, which accepts a replace count?


More information about the Python-ideas mailing list