简体   繁体   中英

python find last in string

I'm looking for a simple method of identifying the last position of a string inside another string ... for instance. If I had: file = C:\\Users\\User\\Desktop\\go.py
and I wanted to crop this so that file = go.py

Normally I would have to run C:\\Users\\User\\Desktop\\go.py through a loop + find statement, and Evey time it encountered a \\ it would ask ... is the the last \\ in the string? ... Once I found the last \\ I would then file = file[last\\:len(file)]
I'm curious to know if there is a faster neater way to do this.. preferably without a loop.
Something like file = [file('\\', last ):len(file)]
If there is nothing like what I've shown above ... then can we place the loop inside the [:] somehow. Something like file = [for i in ...:len(file)]

thanks :)

If it is only about file paths, you can use os.path.basename :

>>> import os
>>> os.path.basename(file)
'go.py'

Or if you are not running the code on Windows, you have to use ntpath instead of os.path .

I agree with Felix on that file paths should be handled using os.path.basename . However, you might want to have a look at the built in string function rpartition .

>>> file = 'C:\Users\User\Desktop\go.py'
>>> before, separator, after = file.rpartition('\\')
>>> before
'C:\\Users\\User\\Desktop'
>>> separator
'\\'
>>> after
'go.py'

There's also the rfind function which gives you the last index of a substring.

>>> file.rfind('\\')
21

I realize that I'm a bit late to the party, but since this is one of the top results when searching for eg "find last in str python" on Google, I think it might help someone to add this information.

You could split the string into a list then get the last index of the list.

Sample:

>>> file = 'C:\Users\User\Desktop\go.py'
>>> print(file.split('\\')[-1])
go.py

For the general purpose case (as the OP said they like the generalisation of the split solution)...... try the rfind(str) function.

"myproject-version2.4.5.customext.zip".rfind(".")

edit: apologies, I hadn't realized how old this thread was... :-/

For pathname manipulations you want to be using os.path .

For this specific problem you want to use the os.path.basename(path) function which will return the last component of a path, or an empty string if the path ends in a slash (ie. the path of a folder rather than a file).

import os.path

print os.path.basename("C:\Users\User\Desktop\go.py")

Gives:

go.py

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