如何去除空行(包含或不包含空格)

51 投票
13 回答
219065 浏览
提问于 2025-04-16 04:08

我有一个很长的字符串,我是通过换行符把它分开的。
我想要删除所有空行(也就是只有空格的行)。

伪代码:

for stuff in largestring:
   remove stuff that is blank

13 个回答

27

我也试过正则表达式和列表的方法,结果列表的方法更快

这是我的解决方案(参考了之前的回答):

text = "\n".join([ll.rstrip() for ll in original_text.splitlines() if ll.strip()])
72

试试列表推导式和 string.strip() 这个方法:

>>> mystr = "L1\nL2\n\nL3\nL4\n  \n\nL5"
>>> mystr.split('\n')
['L1', 'L2', '', 'L3', 'L4', '  ', '', 'L5']
>>> [line for line in mystr.split('\n') if line.strip()]
['L1', 'L2', 'L3', 'L4', 'L5']
52

使用正则表达式:

if re.match(r'^\s*$', line):
    # line is empty (has only the following: \t\n\r and whitespace)

使用正则表达式加上 filter()

filtered = filter(lambda x: not re.match(r'^\s*$', x), original)

codepad 上可以看到。

撰写回答