python在字符串中查找最后一个 [英] python find last in string
问题描述
例如,我正在寻找一种简单的方法来识别一个字符串在另一个字符串内的最后位置.如果我有: file = C:\ Users \ User \ Desktop \ go.py
我想裁剪它,以便 file = go.py
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
通常,我必须通过循环+ find语句运行 C:\ Users \ User \ Desktop \ go.py
,并在遇到它时遇到 \
会问...字符串中的最后一个 \
吗?...找到最后一个 \
后,我将 file = file [last \:len(file)]
我很好奇,是否有更快的方法可以做到这一点..最好不要循环.
例如file = [file('\',
last ):len(file)]
如果没有上面显示的内容,那么可以将循环以某种方式放置在 [:]
内.类似于 file = [for i in ...:len(file)]
谢谢:)
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'
或者,如果您不在Windows上运行代码,则必须使用 ntpath
而不是 os.path
.
Or if you are not running the code on Windows, you have to use ntpath
instead of os.path
.
这篇关于python在字符串中查找最后一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!