2017-03-31 23 views
0

所以我試圖解決一個問題,在我的代碼中,一旦使用了re.split(regex_pattern,str),將額外的反斜槓添加到我的分割列表中的子字符串中。問題是這樣的:當使用re.split時,爲什麼在列表中的子串中添加了一個額外的反斜槓''?

In [63]: str = r'/dir/hello\/hell/dir2/hello\end' 

In [64]: regex_pattern = '(hello)' 

In [65]: a = re.split(regex_pattern, str) 

In [66]: a 
Out[66]: ['/dir/', 'hello', '\\/hell/dir2/', 'hello', '\\end'] 

正如你所看到的,出[66]可見名單爲具有兩個子與「\\」,而不是兩個用「\」。我知道這個問題與編譯器如何解釋反斜槓有關,但最終無法弄清楚爲什麼會發生這種情況。

我也試圖使我str變量原始字符串,並增加額外的「\」我str變量(最多四個「\\\\」),其中一個存在,即

In [63]: str = r'/dir/hello\\/hell/dir2/hello\\end' 

這仍然給出相同的輸出。

我在Ubuntu上使用Python 2.7。對不起,如果這是重複的,但我找不到答案適用於我的問題。

+1

基本上不用擔心。它只是在您將列表打印到屏幕上時改變列表的顯示方式,但實際的字符串沒有任何額外的斜線。 –

+0

@ juanpa.arrivillaga謝謝 –

回答

2

這與re.split沒有任何關係。 \通常定義一個轉義序列。要使用文字\你需要加倍:

考慮您的原始字符串:

In [15]: s = r'/dir/hello\/hell/dir2/hello\end' 

In [16]: s 
Out[16]: '/dir/hello\\/hell/dir2/hello\\end' 

In [17]: len(s) 
Out[17]: 31 

額外\不與len計數。它們只能幫助指定\未定義任何其他轉義序列;旁白\\這也是一個轉義序列。

+0

謝謝。很好的指出它是如何不影響len()的! –

相關問題