我想按个别换行符或空格组拆分一个字符串。我得到了结果,除了''
字符串。我如何消除这些?为什么我在这里得到空白字符串?
编辑:我需要输出保留空白组并分割每个换行符。唯一不需要的东西是''
。
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]' –