简体   繁体   中英

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.

你可以这样做:

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

Try this

url = 'https://twitter.com/shiromiru36/status/1302713597521403904/photo/1'
url=(((url[::-1]).split('/',2))[-1])[::-1]
print(url)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM