假設我有一個字符串/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」的一部分?
假設我有一個字符串/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」的一部分?
就快:
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' 。
謝謝,這是我正在尋找的... –
如果是'/ Apath1/Bpath2/Cpath3/10-1-2-3-4-5-something.otherhing''怎麼辦? –
@ bradley.ayers - 然後他會得到'10-1-2-3-4-5',就像預期的一樣。 – tjameson
使用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'
+1我覺得我比我更喜歡這個。 'rsplit'比切片IMO更清潔。 – tjameson
這工作:
>>> 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混亂)
你可以使用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'
雖然稍微複雜一些,它看起來像與此類似的解決方案可能會稍微更強大......
'os.path.split'? –
你想如何確定要提取什麼?你說你想提取「0-1-2-3-4-5」,但是你怎麼看待它,這就是你想要提取的?如果字符串中還有另一個連字符? – BrenBarn