如何在保留空行的同时拆分?

How to split while keeping the empty line?

例如

'a b\n\n\nc'.split()

给予

['a', 'b', 'c']

我想

['a','b','','','c']

有什么想法吗?

使用re.split

re.split(r'[ \t]', s)

这会在空格或制表符上进行拆分。

使用 - .split('\n')

示例 -

>>> 'a\n\n\nb'.split('\n')
['a', '', '', 'b']

split() 被所有空格分割,因此你不会得到中间的行,相反你可以发送 \n 作为参数来分割,告诉它在每个 \n.

使用str.splitlines. Check the docs and you'll see that it splits on other newline-like characters too. If you want it to only split on \n then use str.split("\n")

>>> "a\n\n\nb".splitlines()
['a', '', '', 'b']

使用str.splitlines():

>>> 'a\n\n\nb'.splitlines()
['a', '', '', 'b']