2017-03-09 84 views
1

我想按個別換行符或空格組拆分一個字符串。我得到了結果,除了''字符串。我如何消除這些?爲什麼我在這裏得到空白字符串?

編輯:我需要輸出保留空白組並分割每個換行符。唯一不需要的東西是''

In [208]: re.split('(\n|\ +)', 'many fancy word \n\n hello \t hi') 
Out[208]: 
['many', 
' ', 
'fancy', 
' ', 
'word', 
' ', 
'', 
'\n', 
'', 
'\n', 
'', 
' ', 
'hello', 
' ', 
'\t', 
' ', 
'hi'] 
+0

因爲'()'是*捕獲組*。使用'(?:\ n | \ +)'將其定義爲*非捕獲組*。 –

+0

@WillemVanOnsem對不起,我沒有明確我的要求。請參閱更新。 – aitchnyu

+0

請參閱https://ideone.com/MB5TQ3,使用'[x for x in re.split('(\ n | +)','許多花哨的詞\ n \ n hello \ t hi')if x]' –

回答

2

如果模式包括捕獲組,那些分隔符將包含在結果列表中。

如果不使用捕獲組或更換與非捕獲組((?:...))捕獲組((...)),分離器不包括在內。

# Not using group at all 
>>> re.split('\n|\ +', 'many fancy word \n\n hello \t hi') 
['many', 'fancy', 'word', '', '', '', 'hello', '\t', 'hi'] 


# Using non-capturing group 
>>> re.split('(?:\n|\ +)', 'many fancy word \n\n hello \t hi') 
['many', 'fancy', 'word', '', '', '', 'hello', '\t', 'hi'] 

報價re.split document

通過模式的出現將字符串分割。 如果在模式中使用捕獲圓括號 ,則模式中所有組的文本均爲 也作爲結果列表的一部分返回。如果maxsplit不爲零,則最多發生maxsplit分裂,並且字符串的其餘部分爲 ,作爲列表的最後一個元素返回。


UPDATE根據問題編輯:

可以使用filter(None, ..)過濾空串出:

list(filter(None, re.split('(\n|\ +)', 'many fancy word \n\n hello \t hi'))) 

或使用re.findall改良模式:

+0

對不起,我沒有明確我的要求。請參閱更新。 – aitchnyu

+0

@aitchnyu,'filter(None,re.split('(\ n | \ +)','很多花哨的詞\ n \ n你好\'嗨'))'給你你想要的? (如果你使用python 3.x,用'list(..)'包裝結果) – falsetru

+0

我認爲你只需要在捕獲組中包裝空間匹配模式。 –

相關問題