开发者

python find last in string

I'm looking for a simple m开发者_开发知识库ethod 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.


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


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 e.g. "find last in str python" on Google, I think it might help someone to add this information.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜