2017-02-27 32 views
-3

如標題所示,re.split("\W")re.split("\w")相同,因爲我得到的結果與我使用的相同。如果它有+也是如此。這是正確的嗎?或者它在某些情況下有效,如果是,爲什麼?先謝謝你。is re.split(「 W」)= re.split(「 w」)?

+3

他們是不一樣的,他們是對立的。顯示輸入字符串以使問題更清晰 – RomanPerekhrest

回答

1

他們不是在所有同一件事:

>>> test_string = 'hello world' 
>>> import re 
>>> re.split('\w', test_string) 
['', '', '', '', '', ' ', '', '', '', '', ''] 
>>> re.split('\W', test_string) 
['hello', 'world'] 

re.split執行以下操作:

分割得到的圖案, 返回包含所產生的子列表的發生源字符串。

\w\W是:

\w  Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]. 
     With LOCALE, it will match the set [0-9_] plus characters defined 
     as letters for the current locale. 
\W  Matches the complement of \w. 
+0

我建議使用'\ W +',因爲它更通用。例如,如果你有「倫敦,英國」,它會返回'['倫敦','美國','王國']。如果沒有'+',它會返回:'['London','','United','Kingdom']'(注意多餘的空字符串)。 –