我想按個別換行符或空格組拆分一個字符串。我得到了結果,除了''
字符串。我如何消除這些?爲什麼我在這裏得到空白字符串?
編輯:我需要輸出保留空白組並分割每個換行符。唯一不需要的東西是''
。
In [208]: re.split('(\n|\ +)', 'many fancy word \n\n hello \t hi')
Out[208]:
['many',
' ',
'fancy',
' ',
'word',
' ',
'',
'\n',
'',
'\n',
'',
' ',
'hello',
' ',
'\t',
' ',
'hi']
因爲'()'是*捕獲組*。使用'(?:\ n | \ +)'將其定義爲*非捕獲組*。 –
@WillemVanOnsem對不起,我沒有明確我的要求。請參閱更新。 – aitchnyu
請參閱https://ideone.com/MB5TQ3,使用'[x for x in re.split('(\ n | +)','許多花哨的詞\ n \ n hello \ t hi')if x]' –