Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the last substring after a character

Tags:

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)?

like image 763
Ziva Avatar asked Jul 27 '14 23:07

Ziva


People also ask

How do you get the string after a certain character?

To get the substring after a specific character, call the substring() method, passing it the index after the character's index as a parameter. The substring method will return the part of the string after the specified character. Copied! We used the String.

How do you find the last instance of a character in a string?

The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .

How do you get a string after a specific character in Python?

First, we have printed the original string and the split word. We then performed the partition function to divide the string. This function will get a string after the substring occurrence. After performing the partition function on the initialized string, print the result in the last line of code.


Video Answer


2 Answers

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 
like image 55
Martijn Pieters Avatar answered Oct 19 '22 06:10

Martijn Pieters


You can do this as well -

str_mine = 'folder1/folder2/folder3/new_folder/image.jpg'     print str_mine.split('/')[-1]  >> image.png 
like image 43
Darpan Avatar answered Oct 19 '22 04:10

Darpan