Remove a part of a path separated with dots

Viewed 979

Given a path, e.g.

file_path = 'a.b.c.d.e'

I wish to remove the e.
This is what I did:

class_path = ('.').join(file_path.split('.')[0:-1])

Any more elegant way to do it?

3 Answers
import os
os.path.splitext(file_path)[0]

Simply with str.rfind function:

file_path = 'a.b.c.d.e'
file_path = file_path[:file_path.rfind('.')+1]
print(file_path)   # a.b.c.d.

If trailing . is not needed - remove +1 shifting: (file_path[:file_path.rfind('.')]).

You could use rpartition for example, if you want to stick to string methods:

class_path = file_path.rpartition('.')[0]
Related