This is a proposal to change the behaviour of the startswith() and
endswith() methods for str, bytes and bytearray objects, making them
return the matched value instead of the True boolean.

Here a str example with the endswith() method:

domain = "python.org"

if domain.endswith(".fr"):
    print(".fr")
elif domain.endswith(".com"):
    print(".com")
elif domain.endswith("org"):
    print(".org")

With the ".org" non-empty str returned by the endswith() method
instead of the True boolean, the above code will work in the same
manner; moreover as startswith() and endswith() methods support a
tuple as argument, and as the PEP 572 walrus operator is supported
since Python 3.8, we can now write this code in a more compact and
pythonic way:

if suffix := domain.endswith((".fr", ".com", ".org"):
    print(suffix)

As the PEP 616 new methods removeprefix() and removesuffix() don't
support a tuple as argument, it will provide a nice and pythonic way
to do it:

if suffix := domain.endswith((".fr", ".com", ".org"):
    print(domain[:-len(suffix)])

Hope I don't miss something obvious and that this proposal could
interest some people.

Best regards

Florent
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/2HTI6GKQPXGHTJKAI2OOJNZDUMIN2BUT/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to