30 Mar
2019
30 Mar
'19
1:29 p.m.
On 3/30/19 9:03 AM, David Mertz wrote:
On Sat, Mar 30, 2019, 8:42 AM Steven D'Aprano <steve@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. ;-) Dan