[Python-ideas] New explicit methods to trim strings

MRAB python at mrabarnett.plus.com
Sat Mar 30 15:26:25 EDT 2019


On 2019-03-30 13:03, David Mertz wrote:
> On Sat, Mar 30, 2019, 8:42 AM Steven D'Aprano <steve at pearwood.info 
> <mailto:steve at pearwood.info>> wrote:
> 
>     Most of us have had to cut a prefix or a suffix from a string, often a
>     file extension. Its not as common as, say, stripping whitespace, but
>     it happens often enough.
> 
> 
> I do this all the time! I never really thought about wanting a method 
> though. I just spell it like this without much thought:
> 
>    basename = fname.split(".ext")[0]
> 
> But I suppose a method would be helpful. If we have one, PLEASE no 
> variation of 'trim' in the name. I still forget whether it's .lstrip() 
> or .ltrim() or .stripl() or etc. after 20 years using Python. Lots of 
> languages use trim for Python's strip, so having both with subtly 
> different meanings is a bug magnet.
> 
> One thing I love about .startswith() and .endswith() is matching 
> multiple options. It's a little funny the multiple options must be a 
> tuple exactly (not a list, not a set, not an iterator), but whatever. It 
> would be about to lack that symmetry in the .cut_suffix() method.
> 
> E.g now:
> 
>    if fname.endswith(('.jpg', '.png', '.gif)): ...
> 
> I'd expect to be able to do:
> 
>    basename = fname.cut_suffix(('.jpg', '.png', '.gif))
> 
I'd much prefer .lcut/.rcut to .cut_prefix/.cut_suffix, to match 
.lstrip/.rstrip.


More information about the Python-ideas mailing list