[Python-ideas] New explicit methods to trim strings

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Mon Apr 1 02:00:16 EDT 2019


On 3/31/19 1:48 AM, Chris Angelico wrote:

 > > * strip_prefix/strip_suffix

I don't like "strip" because .strip already has a different meaning,
although the inclusion of prefix/suffix makes the intended sematics
clear enough for the new methods.  I wonder if it might make the
semantics of .strip even harder to learn, though.

 > > * cut_prefix/cut_suffix
 > > * cut_start/cut_end

Substitute "trim" or "crop" for "cut" in any of the above, because
"cut" might mean "split".  I don't think it's very important, and
prefer "cut" because it will come early in an alphabetical list of
public string methods (discoverability for the new methods).

 > > * Any of the above with the underscore removed
 > > * lcut/rcut
 > > * ltrim/rtrim (and maybe trim)
 > > * truncate (end only, no from-start equivalent)

Dan Sommers writes:

 > without_prefix
 > without_suffix
 > 
 > They're a little longer, but IMO "without" helps
 > reenforce the immutability of the underlying string.  None
 > of these functions actually remove part of the original
 > string, but rather they return a new string that's the
 > original string without some piece of it.

I think this rationale is plausible but don't think it's important
enough to justify the additional length over "cut".

Another possibility to address this would be to use past tense:

prefix_trimmed
prefix_cut                # I think this is awkward.

but writing it out makes me think "nah".

Regarding allowing a tuple argument, I don't see any reason not to
take the "cut the first matching affix and return what's left"
semantics, which is closely analogous to how startswith/endswith work.
As long as the verb isn't "strip", of course.  For me, this
possibility puts the last nail in any variation on "strip".  I don't
see a good reason for the "longest match" variation, except the
analogy to POSIX sematics for regexps, which seems pretty weak to me.

Steve




More information about the Python-ideas mailing list