如何在某个字符最后一次出现后拆分字符串

2024-06-16 11:13:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个网址

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

我需要删除最后一个“/”之后的所有内容,最好在字符串中保留“/”,只删除“1.jpg”。我在网上找不到任何答案,这是我最后的选择


Tags: 字符串答案https内容netjpg网址nhentai
3条回答
  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

如果只是针对这个特定的URL,您可以做一个切片:

>>> print('https://i.nhentai.net/galleries/1545079/1.jpg'[:-5])
https://i.nhentai.net/galleries/1545079/

从最后一个索引到第一个索引运行循环,并在第一次出现“/”时停止。然后构建一个新的字符串到该索引

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

相关问题 更多 >