2017-09-14 92 views
4

我需要确定一些PowerShell路径字符串跨越Python的位置。Python匹配'。'在字符串开头

如何检测Python中的路径是否以.\开头?

下面是一个例子:

import re 

file_path = ".\reports\dsReports" 

if re.match(r'.\\', file_path): 
    print "Pass" 
else: 
    print "Fail" 

失败,在调试器中它列出

expression = .\\\\\\ 
    string = .\\reports\\\\dsReports 

如果我尝试使用像这样替换:

import re 

file_path = ".\reports\dsReports" 
testThis = file_path.replace(r'\', '&jkl$ff88') 

if re.match(r'.&jkl$ff88', file_path): 
    print "Pass" 
else: 
    print "Fail" 

testThis变量结束像这样:

testThis = '.\\reports&jkl$ff88dsReports' 

相当严重。

+1

为什么不能用“如果'。''== file_path [0:2]“或”if'。''in file_path“? – Mike

+0

通常,对Windows路径使用原始字符串,而不仅仅是正则表达式模式。在这种情况下,路径中的\ r被转换为回车符,但还有很多其他组合会出现类似的问题(例如'\ a','\ b','\ f','\ n ''\ t','\ v','\ x'和Python 3'str'和Python 2'unicode'文字,'\ u','\ U')。 – ShadowRanger

回答

5

发生这种情况的原因是因为\r是一个转义序列。你需要他们加倍要么逃避反斜杠,或使用原始字符串字面量是这样的:

file_path = r".\reports\dsReports" 

然后检查是否有".\\"开始:

if file_path.startswith('.\\'): 
    do_whatever() 
+1

或者以'r'开头。'' – donkopotamus

+0

这给了我'SyntaxError:EOL while scanning string literal' –

+3

@donkopotamus:原始字符串文字不能以单个反斜杠结尾;反斜杠可以防止'''被解释为文字的末尾。 – user2357112