New submission from Dennis Sweeney <sweeney.dennis...@gmail.com>:

Following discussion here ( 
https://mail.python.org/archives/list/python-id...@python.org/thread/RJARZSUKCXRJIP42Z2YBBAEN5XA7KEC3/
 ), there is a proposal to add new methods str.cutprefix and str.cutsuffix to 
alleviate the common misuse of str.lstrip and str.rstrip.

I think sticking with the most basic possible behavior

    def cutprefix(self: str, prefix: str) -> str:
        if self.startswith(prefix):
            return self[len(prefix):]
        # return a copy to work for bytearrays
        return self[:]

    def cutsuffix(self: str, suffix: str) -> str:
        if self.startswith(suffix):
            # handles the "[:-0]" issue
            return self[:len(self)-len(suffix)]
        return self[:]

would be best (refusing to guess in the face of ambiguous multiple arguments). 
Someone can do, e.g.

    >>> 'foo.tar.gz'.cutsuffix('.gz').cutsuffix('.tar')
    'foo'

to cut off multiple suffixes. More complicated behavior for multiple arguments 
could be added later, but it would be easy to make a mistake in prematurely 
generalizing right now.

In bikeshedding method names, I think that avoiding the word "strip" would be 
nice so users can have a consistent feeling that "'strip' means character sets; 
'cut' means substrings".

----------
components: Interpreter Core
messages: 363958
nosy: Dennis Sweeney
priority: normal
severity: normal
status: open
title: Add str methods to remove prefixes or suffixes
type: enhancement
versions: Python 3.9

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue39939>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to