python 查找字符串中的最后一个
我正在寻找一种简单的方法来识别另一个字符串中一个字符串的最后位置......例如。如果我有:file = C:\Users\User\Desktop\go.py
我想裁剪它,以便 file = go.py
通常我必须通过以下方式运行 C:\Users\User\Desktop\go.py
Loop + find 语句,每次遇到 \
时它都会问...是字符串中的最后一个 \
吗? ...一旦找到最后一个 \
我就会 file = file[last\:len(file)]
我很想知道是否有更快更简洁的方法来做到这一点..最好没有循环。
类似于 file = [file('\',
last):len(file)]
如果没有像我上面显示的那样......那么我们可以以某种方式将循环放置在 [:]
内。类似于 file = [for i in ...:len(file)]
谢谢 :)
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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果仅涉及文件路径,则可以使用
os .path.basename
:或者,如果您不在 Windows 上运行代码,则必须使用
ntpath
而不是os.path
。If it is only about file paths, you can use
os.path.basename
:Or if you are not running the code on Windows, you have to use
ntpath
instead ofos.path
.您可以将字符串拆分为列表,然后获取列表的最后一个索引。
样本:
You could split the string into a list then get the last index of the list.
Sample:
我同意 Felix 的观点,即文件路径应该使用 os.path.basename 来处理。但是,您可能想查看内置字符串函数
rpartition
。还有
rfind
函数,它可以为您提供子字符串的最后一个索引。我意识到我参加聚会有点晚了,但由于这是在 Google 上搜索“find last in str python”时的最佳结果之一,我认为这可能会帮助某人添加此信息。
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 functionrpartition
.There's also the
rfind
function which gives you the last index of a substring.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.
对于通用情况(正如OP所说,他们喜欢拆分解决方案的泛化)……尝试 rfind(str) 函数。
编辑:抱歉,我没有意识到这个线程有多久了......:-/
For the general purpose case (as the OP said they like the generalisation of the split solution)...... try the
rfind(str)
function.edit: apologies, I hadn't realized how old this thread was... :-/
对于路径名操作,您需要使用
os.path
。对于这个特定问题,您需要使用
os.path .basename(path)
函数将返回路径的最后一个组成部分,如果路径以斜杠结尾(即文件夹而不是文件的路径),则返回空字符串。给出:
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).Gives: