[issue39939] Add str methods to remove prefixes or suffixes
Dennis Sweeney
report at bugs.python.org
Wed Mar 11 15:11:38 EDT 2020
New submission from Dennis Sweeney <sweeney.dennis650 at gmail.com>:
Following discussion here ( https://mail.python.org/archives/list/python-ideas@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 <report at bugs.python.org>
<https://bugs.python.org/issue39939>
_______________________________________
More information about the Python-bugs-list
mailing list