[英]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.