Find the last substring after the character

I know many ways to find a substring: from the beginning of the index to the end, between characters, etc., but I have a problem that I do not know how to solve: I have a line, for example, the path: folder1/folder2/folder3/new_folder/image.jpg and the second path: folder1/folder2/folder3/folder4/image2.png

And from these paths I want to take only the last parts: image.jpg and image2.png . How can I take a substring if I do not know when it will start (I do not know the index, but I can assume that it will be after the last / character), if one character ( / ) is repeated many times, and the extensions differ ( .jpg and .png and even others)?

+7
python string substring regex
source share
3 answers

Use os.path.basename() and don't worry about the details.

os.path.basename() returns the file name part of your path:

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

For a more general line break problem, you can use str.rpartition() to split a string into a given sequence of characters, starting at the end:

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

and str.rsplit() you can split several times to the limit, again from the end:

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

And last but not least, you can use str.rfind() to find only the substring index, search from the end:

 >>> 'foo:bar:baz'.rfind(':') 7 
+14
source share

You can also do this -

 str_mine = 'folder1/folder2/folder3/new_folder/image.jpg' print str_mine.split('/')[-1] >> image.png 
+2
source share
  import re pattern=re.compile(r"(.*?)/([a-zA-Z0-9]+?\.\w+)") y=pattern.match(x).groups() print y[1] 

No length restrictions.

+1
source share

All Articles