python在字符串中查找最后一个 [英] python find last in string

查看:292
本文介绍了python在字符串中查找最后一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我正在寻找一种简单的方法来识别一个字符串在另一个字符串内的最后位置.如果我有: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆