How to remove empty lines with or without whitespace in Python
Try list comprehension and 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']
Using regex:
if re.match(r'^\s*$', line):
# line is empty (has only the following: \t\n\r and whitespace)
Using regex + filter()
:
filtered = filter(lambda x: not re.match(r'^\s*$', x), original)
As seen on codepad.
I also tried regexp and list solutions, and list one is faster.
Here is my solution (by previous answers):
text = "\n".join([ll.rstrip() for ll in original_text.splitlines() if ll.strip()])
lines = bigstring.split('\n')
lines = [line for line in lines if line.strip()]