如何在Python中删除带或不带空格的空行 [英] How to remove empty lines with or without whitespace in Python
本文介绍了如何在Python中删除带或不带空格的空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有大字符串,我用换行符分割.如何删除所有空行(仅限空格)?
I have large string which I split by newlines. How can I remove all lines that are empty, (whitespace only)?
伪代码:
for stuff in largestring:
remove stuff that is blank
推荐答案
使用正则表达式:
if re.match(r'^\s*$', line):
# line is empty (has only the following: \t\n\r and whitespace)
使用正则表达式 + filter()
:
Using regex + filter()
:
filtered = filter(lambda x: not re.match(r'^\s*$', x), original)
如在 codepad 上所见.
这篇关于如何在Python中删除带或不带空格的空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文