[Python-ideas] New explicit methods to trim strings
MRAB
python at mrabarnett.plus.com
Sun Mar 31 12:08:00 EDT 2019
On 2019-03-31 16:48, David Mertz wrote:
> The only reason I would support the idea would be to allow multiple
> suffixes (or prefixes). Otherwise, it just does too little for a new
> method. But adding that capability of startswith/endswith makes the cut
> off something easy to get wrong and non-trivial to implement.
>
> 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 semantics or removals where one is a substring of another would
> need to be decided. As long as it's documented, any behavior would be
> fine. Most of the time the issue would be moot.
> > On Sun, Mar 31, 2019, 4:36 AM Steven D'Aprano <steve at pearwood.info
> <mailto: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.
>
More information about the Python-ideas
mailing list