2016-04-18 90 views
1

在Python中,是否有簡單的方法可以提取看起來像大字符串路徑的字符串?從字符串中提取像字符串的路徑

例如,如果:

A = "This Is A String With A /Linux/Path" 

什麼在我的方式!展望提取物:

"/Linux/Path" 

我也喜歡它是獨立於操作系統的,所以如果:

A = "This is A String With A C:\Windows\Path" 

我想提取:

"C:\Windows\Path" 

我猜測有一種方法可以用正則表達式尋找/\,但我只是想知道是否有更多pythonic的方式?

我很高興冒着/\可能存在於主字符串的另一部分的風險。

回答

1

您可以在os.sep分開,並採取了比一個更長的結果:

import os 

def get_paths(s, sep=os.sep): 
    return [x for x in s.split() if len(x.split(sep)) > 1] 

在Linux/OSX:

>>> A = "This Is A String With A /Linux/Path" 
>>> get_paths(A) 
['/Linux/Path'] 

對於多條路徑:

>>> B = "This Is A String With A /Linux/Path and /Another/Linux/Path" 
>>> get_paths(B) 
['/Linux/Path', '/Another/Linux/Path'] 

嘲諷Windows:

>>> W = r"This is A String With A C:\Windows\Path" 
>>> get_paths(W, sep='\\') 
['C:\\Windows\\Path'] 
+0

感謝您的快速回復 - 這應該是一種享受! – Mark