Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract substring from string, python

Tags:

python

string

I have a path to some file:

'home/user/directory/filename'

I want get the filename-subpart. The main problem is, I don't know the length of my string and I don't know the length of filename-subpart. I know just that filename is placed at the end of a string after the last slash /. The number of slashes in the string could be absolutely random (because I want get the filename from every directory on some PC). Consequently I don't see for now the usual method with index extraction, like this:

string[number:]

Any ideas?

like image 716
Guforu Avatar asked Jul 30 '26 20:07

Guforu


1 Answers

To get the basename use os.path.basename:

Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split()

from os import path

pth = 'home/user/directory/filename'
print(path.basename(pth))
filename

Or str.rsplit:

 print(pth.rsplit("/",1)[1])
 filename

If you were trying to index a string from the last occurrence you would use rindex:

print(pth[pth.rindex("/") + 1:])
like image 142
Padraic Cunningham Avatar answered Aug 01 '26 10:08

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!