python - Find the last substring after a character -
I know how to find a substring: from start index to letters between the end, etc., but I have problems Which I do not know how to solve: I have a string, for example a path: folder1 / folder2 / folder3 / new_folder / image.jpg
and another path: folder1 / folder2 /folder3/folder4/image2.png
And from this path I only want to take the previous parts: image.jpg
and image2.png
. If I do not know when it starts (I do not know the index, but I think it will be after the last /
character) How can I get a substrings, if at times Letter repeats ( /
) and extensions are different ( .jpg
and .png
even more)?
os.path.basename ()
Returns the file name of your path: < / P>
& gt; & Gt; & Gt; Import os.path & gt; & Gt; & Gt; Os.path.basename ('Folder 1 / folder2 / folder3 / new_folder / image.jpg') 'image.jpg'
For a more common string splitting problem, you use to split The string on the given alphabet sequence count from the end :
& gt; & Gt; & Gt; 'Foo: bar: baz'.rpartition (': ') (' foo: bar ',': ',' baz ')> gt; & Gt; & Gt; 'Foo: bar: baz'.rpartition (': ') [- 1]' falcon '
and with you several times to a limit, you can redistribute from the end :
& gt; & Gt; & Gt; 'Foo: Bar: Baaz: Spam: Eggs'. Finally, but at least, you search from the end (':', 3) ['Foo: Bar', 'Buzz', 'Spam', 'Egg']
Taxes can find just a substring indicator:
& gt; & Gt; & Gt; 'Foo: Bar: baz'.rfind (': ') 7
Comments
Post a Comment