[Python-ideas] New explicit methods to trim strings

MRAB python at mrabarnett.plus.com
Tue Apr 2 14:33:55 EDT 2019


On 2019-04-02 18:55, Stephen J. Turnbull wrote:
> Rhodri James writes:
> 
> Steven d'Aprano writes:
>   > > (That's over a third of this admittedly incomplete list of prefixes.)
>   > >
>   > > I can think of at least one English suffix pair that clash: -ify, -fy.
> 
> And worse: is "tries" the third person present tense of "try" or is it
> the plural of "trie"?  Pure lexical manipulation can't tell you.
> 
>   > You're beginning to persuade me that cut/trim methods/functions aren't a
>   > good idea :-)
> 
> I don't think I would go there yet (well, I started there, but...).
> 
>   > So far we have two slightly dubious use-cases.
>   >
>   > 1. Stripping file extensions.  Personally I find that treating filenames
>   > like filenames (i.e. using os.path or (nowadays) pathlib) results in me
>   > thinking more appropriately about what I'm doing.
> 
> Very much agree.
> 
>   > 2. Stripping prefixes and suffixes to get to root words.
> 
>      for suffix in english_suffixes:
>          root = word.cutsuffix(suffix)
>          if lookup_in_dictionary(root):
>              do_something_appropriate_with_each_root_found()
> 
> is surely more flexible and accurate than a hard-coded slice, and
> significantly more readable than
> 
>      for suffix in english_suffixes:
>          root = word[:-len(suffix)] if word.endswith(suffix) else word
>          if lookup_in_dictionary(root):
>              do_something_appropriate_with_each_root_found()
> 
[snip]
The code above contains a subtle bug.
If suffix == '', then word.endswith(suffix) == True, and 
word[:-len(suffix)] == word[:-0] == ''.

Each time I see someone do that, I see more evidence in support of 
adding the method.


More information about the Python-ideas mailing list