dunstorm
dunstorm

Reputation: 392

Delete Specific Part Of A String

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 .

Upvotes: 3

Views: 3493

Answers (3)

skovorodkin
skovorodkin

Reputation: 10264

You can also use .rindex string method:

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

Upvotes: 2

badbuddha
badbuddha

Reputation: 1

#!/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()

Upvotes: 0

jezrael
jezrael

Reputation: 862406

Use rsplit:

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

str = "live/examples/myfiles.png"
print (str.rsplit('/', 1)[0] + '/')
live/examples/

Upvotes: 4

Related Questions