2017-02-27 2 views
-3

タイトルが言っているように、re.split("\W")re.split("\w")と同じです。なぜなら、私が得た結果は同じですからです。もしそれが+であれば同じことが起こります。これは正しいですか?または、それはいくつかのケースで動作し、そうならばなぜですか?前もって感謝します。は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 ''を持っていれば '['London'、 'United'、 'Kingdom']'を返します。 '+ 'がなければ、' ['ロンドン '、' '、'ユナイテッド '、'キングダム '] '(余分な空文字列に気付く)を返します。 –

関連する問題