0

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.

Dave
  • 373
  • 1
  • 6
  • 17
  • Does this answer your question? [Splitting on last delimiter in Python string?](https://stackoverflow.com/questions/15012228/splitting-on-last-delimiter-in-python-string) – Florian Winter Oct 28 '20 at 15:32

2 Answers2

7
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

5

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'
>>>>