在字符串中查找最后一个char外观

时间:2012-05-03 18:56:28

标签: python string

如果有此输入:

/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff

我希望找到char "/"最后一次出现,并获取字符串BasicTest

这样做的好方法是什么?

谢谢!

6 个答案:

答案 0 :(得分:5)

os.path模块提供基本的路径名操作。

>>> from os.path import *
>>> file = '/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff'
>>> splitext(basename(dirname(file)))[0]
'BasicTest'

答案 1 :(得分:4)

>>> s = "/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff"
>>> ind = s.rfind('/')
>>> ind1 = s[:ind].rfind('/')
>>> print(s[ind1+1:ind].split('.')[0])
BasicTest

答案 2 :(得分:3)

这是os的一个例子:

>>> p = '/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff'
>>> os.path.dirname(p)
'/Users/myMac/Desktop/MemoryAccess/BasicTest.asm'
>>> os.path.splitext(os.path.dirname(p))
('/Users/myMac/Desktop/MemoryAccess/BasicTest', '.asm')
>>> os.path.basename(os.path.splitext(os.path.dirname(p))[0])
'BasicTest'

答案 3 :(得分:1)

好吧,“BasicTest”遵循“/”的倒数第二次出现,但除此之外,请尝试rfind

答案 4 :(得分:1)

以下将返回BasicTest.asm,这是战斗的一半:

'/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff'.split('/')[-2]

可以使用相同的技巧拆分'。'

'BasicTest.asm'.split('.')[0]

答案 5 :(得分:0)

使用re in python

import re
s = "/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff"
pattern = re.compile(r"/(\w+)\.\w+/\w*$")
match = re.search(pattern,s)
print match.group(1)