簡體   English   中英

如何在某個字符最后一次出現后拆分字符串

[英]How to split string after last appearance of a certain character

我有這個 URL

https://i.nhentai.net/galleries/1545079/1.jpg

而且我需要刪除最后一個“/”之后的所有內容,最好將字符串中的“/”保留為只刪除“1.jpg”。 我在 web 上找不到任何答案,這是我最后的手段。

  1. 使用字符串拆分
  2. 在拆分之間使用“/”重新加入
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM