3

I want to delete the part after the last '/' of a string in this following way:

str = "live/1374385.jpg"
formated_str = "live/"

or

str = "live/examples/myfiles.png"
formated_str = "live/examples/"

I have tried this so far ( working )

import re
for i in re.findall('(.*?)/',str):
    j += i
    j += '/'

Output :

live/ or live/examples/

I am a beginner to python so just curious is there any other way to do that .

6
  • You might want to check How to get everything after last slash in a URL? Commented Sep 30, 2016 at 6:10
  • no opposite of it before the last slash of the url Commented Sep 30, 2016 at 6:14
  • 1
    I am pretty sure you can find the answer by tweaking the accepted answer a bit. Commented Sep 30, 2016 at 6:15
  • @ProFan - Is question marked as duplicated helpful for you? Because I think it is a bit different. Commented Sep 30, 2016 at 6:19
  • 1
    no it's not actually because I wanted to get the URL directory which can't be done using os.path.dirname Commented Sep 30, 2016 at 6:21

3 Answers 3

4

Use rsplit:

str = "live/1374385.jpg"
print (str.rsplit('/', 1)[0] + '/')
live/

str = "live/examples/myfiles.png"
print (str.rsplit('/', 1)[0] + '/')
live/examples/
Sign up to request clarification or add additional context in comments.

Comments

2

You can also use .rindex string method:

s = 'live/examples/myfiles.png'
s[:s.rindex('/')+1]

Comments

0
#!/usr/bin/python

def removePart(_str1):
    return "/".join(_str1.split("/")[:-1])+"/"

def main():
    print removePart("live/1374385.jpg")
    print removePart("live/examples/myfiles.png")

main()

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.