Search code examples
pythontweepy

Get substring from a string with specific pattern


I am working with twitter links and I have extracted the links from twitter's api.

https://twitter.com/shiromiru36/status/1302713597521403904/photo/1

The above is an example of links that I have.

I would like to get front part of the link only, I want to delete

/photo/1

So that I can get

https://twitter.com/shiromiru36/status/1302713597521403904

Currently I extract the link by counting the number of words that I don't want

url = https://twitter.com/shiromiru36/status/1302713597521403904/photo/1
url[:-8]

I would like to ask if there is any way to extract the link by finding its own pattern. As the unwanted part is after the 2nd last "/". I am thinking whether I can delete the unwanted part by finding the 2nd last "/" first, and then delete the words after it.

Thank you.


Solution

  • You could do something like this:

    '/'.join(s.split('/')[:-2])