[Python-ideas] New explicit methods to trim strings
Steven D'Aprano
steve at pearwood.info
Mon Apr 1 22:15:17 EDT 2019
On Mon, Apr 01, 2019 at 09:34:21PM -0400, David Mertz wrote:
> On Mon, Apr 1, 2019, 8:54 PM Steven D'Aprano <steve at pearwood.info> wrote:
>
> > The point I am making is not that we must not ever support multiple
> > affixes, but that we shouldn't rush that decision. Let's pick the
> > low-hanging fruit, and get some real-world experience with the function
> > before deciding how to handle the multiple affix case.
> >
>
> There are exactly two methods of strings that deal specifically with
> affixes currently. Startswith and endswith. Both of those allow specifying
> multiple affixes.
When testing for the existence of a prefix (or suffix), there are no
choices that need to be made for the multiple prefix case.
If spam.startswith("contra"), then it also starts with "co", and we
don't have to decide whether to delete six characters or two.
If spam starts with one of ("de", "ex", "in", "mono"), then it doesn't
matter what order we specify the tests, it will return True regardless.
If you write a pure Python implementation of multiprefix startswith,
there's one *obviously correct* version:
def multi_startswith(astring, prefixes):
return any(astring.prefix for prefix in prefixes)
because it literally doesn't matter which of the prefixes triggered the
match. I could randomize the order of the prefixes, and nothing would
change. But if you delete the prefix, it matter a lot which prefix
triggers the match.
> That's pretty strong real-world experience
But not as strong as str.replace, which is much older than
starts/endswith and still refuses to guess what the user expects to do
with multiple substrings.
--
Steven
More information about the Python-ideas
mailing list