> > One may also continue using ``startswith()``
> > and ``endswith()``
> > methods for control flow instead of testing the lengths as above.
> > That's worse, in a sense, since "foofoobar".removeprefix("foo") returns
> "foobar" which still starts with "foo".
I meant that startswith might be called before removeprefix, as it was
in the ``deccheck.py`` example.
Not having read the full PEP, that wasn't clear to me. Sorry!
> If I saw that in a code review I'd flag it for non-obviousness. One should
> use 'string != new_string' unless there is severe pressure to squeeze
> every nanosecond out of this particular code (and it better be inside an
> inner loop).
I thought that someone had suggested that such things go in the PEP,
I'm sure someone did. But not every bit of feedback is worth acting upon, and sometimes a weird compromise is cooked up that addresses somebody's nit while making things less understandable for everyone else. I think this is one of those cases.
since these are more stylistic considerations, I would be more than happy to
trim it down to just
The builtin ``str`` class will gain two new methods which will behave
as follows when ``type(self) is type(prefix) is str``::
def removeprefix(self: str, prefix: str, /) -> str:
def removesuffix(self: str, suffix: str, /) -> str:
# suffix='' should not call self[:-0].
if suffix and self.endswith(suffix):
These methods, even when called on ``str`` subclasses, should always
return base ``str`` objects.
Methods with the corresponding semantics will be added to the builtin
``bytes`` and ``bytearray`` objects. If ``b`` is either a ``bytes``
or ``bytearray`` object, then ``b.removeprefix()`` and ``b.removesuffix()``
will accept any bytes-like object as an argument. The two methods will
also be added to ``collections.UserString``, with similar behavior.