2016-04-18 92 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