简体   繁体   中英

How to split string after last appearance of a certain character

I have this URL

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

And I need to delete everything after the last "/", preferably leaving the "/" in the string just deleting "1.jpg". I couldn't find any answers on the web, this is my last resort.

  1. use string split
  2. re-join using '/' in between splits
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

Run a loop from last index to first and stop at the first occurence of '/'. Then build a new string up to that index.

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

If its just for this specific URL you could do a slice:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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