[Python-ideas] New explicit methods to trim strings

Dan Sommers 2QdxY4RzWzUUiLuE at potatochowder.com
Sat Mar 30 09:29:15 EDT 2019

On 3/30/19 9:03 AM, David Mertz wrote:
> On Sat, Mar 30, 2019, 8:42 AM Steven D'Aprano <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]

This one also works until it doesn't:

     basename = 'special.extensions.ext'.split(".ext")[0]
     basename = 'food.pyramid.py'.split(".py")[0]
     basename = 'build.classes.c'.split(".c")[0]

Safer is fname.rsplit('.ext', 1)[0].

There's always os.path.splitext.  ;-)


More information about the Python-ideas mailing list