2012-11-26 111 views
0

假設我有一個字符串/Apath1/Bpath2/Cpath3/0-1-2-3-4-5-something.otherthing我想提取'0-1-2-3-4-5'部分。我嘗試這樣做:如何從字符串中提取子字符串?

str='/Apath1/Bpath2/Cpath3/0-1-2-3-4-5-something.otherhing' 

print str[str.find("-")-1:str.find("-")] 

但是,結果只有0.1如何只提取「0-1-2-3-4-5」的一部分?

+0

'os.path.split'? –

+1

你想如何確定要提取什麼?你說你想提取「0-1-2-3-4-5」,但是你怎麼看待它,這就是你想要提取的?如果字符串中還有另一個連字符? – BrenBarn

回答

3

就快:

str='/Apath1/Bpath2/Cpath3/0-1-2-3-4-5-something.otherhing' 
print str[str.find("-")-1:str.rfind("-")] 

rfind將結束搜索。這假設路徑中的其他地方不出現破折號。如果可以做到這一點,而不是:

str='/Apath1/Bpath2/Cpath3/0-1-2-3-4-5-something.otherhing' 
str = os.path.basename(str) 
print str[str.find("-")-1:str.rfind("-")] 

basename會搶了文件名,不包括路徑的其餘部分。這可能是你想要的。

編輯:

正如@ bradley.ayers指出,這打破了在文件名後沒有在這個問題正好說明的情況。由於我們使用basename,我們可以省略開始索引:

print str[:str.rfind("-")] 

這將解析「/Apath1/Bpath2/Cpath3/10-1-2-3-4-5-something.otherhing」爲' 10-1-2-3-4-5' 。

+0

謝謝,這是我正在尋找的... –

+0

如果是'/ Apath1/Bpath2/Cpath3/10-1-2-3-4-5-something.otherhing''怎麼辦? –

+1

@ bradley.ayers - 然後他會得到'10-1-2-3-4-5',就像預期的一樣。 – tjameson

6

使用os.path.basename和rsplit:

>>> from os.path import basename 
>>> name = '/Apath1/Bpath2/Cpath3/0-1-2-3-4-5-something.otherhing' 
>>> number, tail = basename(name).rsplit('-', 1) 
>>> number 
'0-1-2-3-4-5' 
+0

+1我覺得我比我更喜歡這個。 'rsplit'比切片IMO更清潔。 – tjameson

1

這工作:

>>> str='/Apath1/Bpath2/Cpath3/0-1-2-3-4-5-something.otherhing' 
>>> str.split('/')[-1].rsplit('-', 1)[0] 
'0-1-2-3-4-5' 

假設你想要的是最後的「/」,最後只之間什麼是「 - 」。與os.path其他建議可能做出更好的感覺(只要有過什麼AA正確的路徑看起來像沒有OS混亂)

0

你可以使用re

>>> import re 
>>> ss = '/Apath1/Bpath2/Cpath3/0-1-2-3-4-5-something.otherhing' 
>>> re.search(r'(?:\d-)+\d',ss).group(0) 
'0-1-2-3-4-5' 

雖然稍微複雜一些,它看起來像與此類似的解決方案可能會稍微更強大......

相關問題