Reputation: 513
I am trying to slice URLs from the last symbol "/".
For example, I have an URL http://google.com/images/54152352.
Now I need the part of that image which is 54152352.
I understand that I could simply slice it with slicing from a certain character, but I have a list of URLs and each of them is different.
Other examples of URLs:
https://google.uk/images/kfakp3ok2 #I would need kfakp3ok2
bing.com/img/3525236236 #I would need 3525236236
wwww.google.com/img/1osdkg23 #I would need 1osdkg23
Is there a way to slice the characters from the last character "/" in a string in Python3? Each part from a different URL has a different length.
All the help will be appreciated.
Upvotes: 0
Views: 1799
Reputation: 51
You can use the rsplit() functionality.
Syntax: string.rsplit(separator, maxsplit)
Reference https://www.w3schools.com/python/ref_string_rsplit.asp
rsplit() splits the string from the right using the delimiter/separator and using maxsplit you can split only once with some performance benefit as compared to split() as you dont need to split more than once.
>>>> url='https://google.uk/images/kfakp3ok2'
>>>>
>>>> url.rsplit('/', 1)[-1]
'kfakp3ok2'
>>>>
Upvotes: 5
Reputation: 86
target=url.split("/")[-1]
split methode returns a list of words separated by the separator specified in the argument and [-1] is for the last element of that list
Upvotes: 7