如果有这个输入:
/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff
我想找到字符最后一次 "/"
出现的时间,并获取字符串BasicTest
这样做的好方法是什么?
谢谢!
os.path模块提供基本的路径名操作。
>>> from os.path import *
>>> file = '/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff'
>>> splitext(basename(dirname(file)))[0]
'BasicTest'
>>> s = "/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff"
>>> ind = s.rfind('/')
>>> ind1 = s[:ind].rfind('/')
>>> print(s[ind1+1:ind].split('.')[0])
BasicTest
这是 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'
好吧,“BasicTest”紧随“/”的倒数第二个出现,但除此之外,试试rfind
.
以下将返回BasicTest.asm
,这是成功的一半:
'/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff'.split('/')[-2]
可以使用相同的技巧来拆分“。”
'BasicTest.asm'.split('.')[0]
在 python 中使用 re
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)