26

I know many ways how to find a substring: from start index to end index, between characters etc., but I have a problem which I don't know how to solve: I have a string like for example a path: folder1/folder2/folder3/new_folder/image.jpg and the second path: folder1/folder2/folder3/folder4/image2.png

And from this paths I want to take only the last parts: image.jpg and image2.png. How can I take a substring if I don't know when it starts (I don't know the index, but I can suppose that it will be after last / character), if many times one character repeats (/) and the extensions are different (.jpg and .png and even other)?

Ziva
  • 3,181
  • 15
  • 48
  • 80

4 Answers4

39

Use os.path.basename() instead and not worry about the details.

os.path.basename() returns the filename portion of your path:

>>> import os.path
>>> os.path.basename('folder1/folder2/folder3/new_folder/image.jpg')
'image.jpg'

For a more generic string splitting problem, you can use str.rpartition() to split a string on a given character sequence counting from the end:

>>> 'foo:bar:baz'.rpartition(':')
('foo:bar', ':', 'baz')
>>> 'foo:bar:baz'.rpartition(':')[-1]
'baz'

and with str.rsplit() you can split multiple times up to a limit, again from the end:

>>> 'foo:bar:baz:spam:eggs'.rsplit(':', 3)
['foo:bar', 'baz', 'spam', 'eggs']

Last but not least, you could use str.rfind() to find just the index of a substring, searching from the end:

>>> 'foo:bar:baz'.rfind(':')
7
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
23

You can do this as well -

str_mine = 'folder1/folder2/folder3/new_folder/image.jpg'    
print str_mine.split('/')[-1]

>> image.png
Darpan
  • 5,623
  • 3
  • 48
  • 80
6

you can do this split on last occurrence

my_string='folder1/folder2/folder3/new_folder/image2.png'
print(my_string.rsplit("/",1)[1])
output:-
image2.png
outlier
  • 331
  • 3
  • 10
  • 1
    Does this answer add any value than the same answer posted an year ago? – Darpan Jun 19 '19 at 17:52
  • 2
    @Darpan Do you mean [your answer](https://stackoverflow.com/a/43630760/6045800) (suggesting `split('/')[-1]`)? Yes it adds alot. While your answer splits the whole string and takes the last element, this only splits once from the right. A bit more efficient. Even more efficient would be to use `rpartition`... – Tomerikoo Mar 10 '22 at 11:28
1
import re

pattern = re.compile(r"(.*?)/([a-zA-Z0-9]+?\.\w+)")
y = pattern.match(x).groups()
print y[1]

No length constraints.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
vks
  • 67,027
  • 10
  • 91
  • 124