[英]How to split string after last appearance of a certain character
我有这个 URL
https://i.nhentai.net/galleries/1545079/1.jpg
而且我需要删除最后一个“/”之后的所有内容,最好将字符串中的“/”保留为只删除“1.jpg”。 我在 web 上找不到任何答案,这是我最后的手段。
URL = https://i.nhentai.net/galleries/1545079/1.jpg
# considering https:// as every start
URL = URL[8:]
# splits and excludes last item
new_url = URL.split('/')[:-1]
# re-joins the url
new_url = '/'.join(new_url)
# adds constant start
new_url = 'https://' + new_url
从最后一个索引到第一个索引运行一个循环,并在第一次出现“/”时停止。 然后建立一个新的字符串直到该索引。
x = "https://i.nhentai.net/galleries/1545079/1.jpg"
newStr = ""
for i in range(len(x) - 1, 0, -1):
if x[i] == '/':
newStr = x[0:i + 1]
break
如果它只是针对这个特定的 URL 你可以做一个切片:
>>> print('https://i.nhentai.net/galleries/1545079/1.jpg'[:-5])
https://i.nhentai.net/galleries/1545079/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.