1

I have the following:

selstim = '/Users/folder1/folder2/folder9/Pictures/Set_1/Pos/43et1.jpg'

I need to end up with:

43et1

I tried:

selstim.split('/')[-1]

Which produced:

43et1.jpg

I also tried:

selstim.split('/,.')[-1]

That doesn't get the desired result.

Is there a way to also get rid of the '.jpg' in the same line of code?

arkadiy
  • 746
  • 1
  • 10
  • 26

2 Answers2

3

You may just find it easier to use pathlib (if you have Python 3.4+) and let it separate the path components for you:

>>> from pathlib import Path
>>> p = Path('/Users/folder1/folder2/folder9/Pictures/Set_1/Pos/43et1.jpg')
>>> p.stem
43et1
sj95126
  • 6,520
  • 2
  • 15
  • 34
1

Implementation using only the standard os library.

from os import path

filePath = path.basename("/Users/folder1/folder2/folder9/Pictures/Set_1/Pos/43et1.jpg")

print(filePath) # 43et1.jpg
print(path.splitext(filePath)[0]) # 43et1, index at [1] is the file extension. (.jpg)

All in one line:

path.splitext(path.basename(FILE_PATH))[0]
Skully
  • 2,882
  • 3
  • 20
  • 31