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 .

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
dunstorm
  • 372
  • 6
  • 13
  • You might want to check [How to get everything after last slash in a URL?](http://stackoverflow.com/questions/7253803/how-to-get-everything-after-last-slash-in-a-url) – Ozgur Vatansever Sep 30 '16 at 06:10
  • no opposite of it before the last slash of the url – dunstorm Sep 30 '16 at 06:14
  • 1
    I am pretty sure you can find the answer by tweaking the accepted answer a bit. – Ozgur Vatansever Sep 30 '16 at 06:15
  • @ProFan - Is [question](http://stackoverflow.com/questions/33372054/get-folder-name-of-the-file-in-python) marked as duplicated helpful for you? Because I think it is a bit different. – jezrael Sep 30 '16 at 06:19
  • 1
    no it's not actually because I wanted to get the URL directory which can't be done using `os.path.dirname` – dunstorm Sep 30 '16 at 06:21
  • _Why_ can't it be done with `os.path.dirname`? It seems to work perfectly. Specify why it's unsuitable. – TigerhawkT3 Sep 30 '16 at 06:59

3 Answers3

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/
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

You can also use .rindex string method:

s = 'live/examples/myfiles.png'
s[:s.rindex('/')+1]
skovorodkin
  • 9,394
  • 1
  • 39
  • 30
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()
badbuddha
  • 1
  • 3
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) 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. – andreas Sep 30 '16 at 09:20