[Python-ideas] New explicit methods to trim strings

Cameron Simpson cs at cskk.id.au
Sun Mar 24 19:45:49 EDT 2019

On 24Mar2019 18:39, MRAB <python at mrabarnett.plus.com> wrote:
>On 2019-03-24 08:42, Alex Grigoryev wrote:
>>Following the discussion here <https://link.getmailspring.com/link/7D84D131-65B6-4EF7-9C43-51957F9DFAA9@getmailspring.com/0?redirect=https%3A%2F%2Fbugs.python.org%2Fissue36410&recipient=cHl0aG9uLWlkZWFzQHB5dGhvbi5vcmc%3D> 
>This has a subtle bug:
>>In [2]: def rtrim(s, seq):
>>    ...:     return s[:-len(seq)] if s.endswith(seq) else s
>>    ...:
>If len(seq) == 0, then rtrim will return ''.
>It needs to be:
>def rtrim(s, seq):
>    return s[ : len(s) - len(seq)] if s.endswith(seq) else s


    return s[:-len(seq)] if seq and s.endswith(seq) else s

which I think more readable.

For the record, like others, I suspect I've written ltrim/rtrim code 
many times.

I'm +0.9 on the idea: it feels like a very common operation and as shown 
above rtrim at least is fairly easily miscoded. (I think most of my own 
situations were with strings I know are not empty, often literals, but 
that doesn't really detract.)

Like others I'm against the name 'trim" itself because of PHP's homonym 
which means what "strip" means in Python (and therefore doesn't mean 
what "trim" is proposed to mean here). "clip"?

I'm +0.9 rather than +1 entirely because the operation feels so...  
trivial, which usually trips the "not everything needs a method" 
argument.  But it is also very common.

Cameron Simpson <cs at cskk.id.au>

More information about the Python-ideas mailing list