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.

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.