简体   繁体   English

从具有特定模式的字符串中获取子字符串

[英]Get substring from a string with specific pattern

I am working with twitter links and I have extracted the links from twitter's api.我正在使用 twitter 链接,我已经从 twitter 的 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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