[Fixed]-How to get the substring from a String in python

-1๐Ÿ‘

โœ…

If you need to match the exact extension:
# (?<=/) ensure that before the match is / 
# [^/]*.xlsx search for anything but / followed by .xlsx
mo1 = re.search('(?<=/)[^/]*.xlsx', path).group(0)
print(mo1)
My_file.xlsx

otherwise:

path='/home/user/Desktop/My_file.xlsx'

with regex:

mo = re.search(r'(?<=/)([\w.]+$)',path)
print(mo.group(1))
My_file.xlsx

with rsplit:

my_file = path.rsplit('/')[-1]
print(my_file)
My_file.xlsx
๐Ÿ‘คLetzerWille

2๐Ÿ‘

If you know that the file extension is always the same (e.g. โ€œ.xlsxโ€) I would suggest you to go this way:

import os
filename_full = os.path.basename(path)
filename = filename_full.split(".xlsx")[0]

Hope it helps

๐Ÿ‘คFSp

0๐Ÿ‘

More generally:

import os
filename = os.path.basename(os.path.splitext(path)[0])
๐Ÿ‘คalbar

Leave a comment