I have large string which I split by newlines. How can I remove all lines that are empty, (whitespace only)?
pseudo code:
for stuff in largestring:
remove stuff that is blank
Join Stack Overflow to learn, share knowledge, and build your career.
I have large string which I split by newlines. How can I remove all lines that are empty, (whitespace only)?
pseudo code:
for stuff in largestring:
remove stuff that is blank
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.
1000 loops, best of 3: 452 us per loop
; join, split & strip: 100000 loops, best of 3: 5.41 us per loop
– m01
May 28 '13 at 8:48
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']
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()]
Surprised a multiline re.sub has not been suggested (Oh, because you've already split your string... But why?):
>>> import re
>>> a = "Foo\n \nBar\nBaz\n\n Garply\n \n"
>>> print a
Foo
Bar
Baz
Garply
>>> print(re.sub(r'\n\s*\n','\n',a,re.MULTILINE))
Foo
Bar
Baz
Garply
>>>
If you are not willing to try regex (which you should), you can use this:
s.replace('\n\n','\n')
Repeat this several times to make sure there is no blank line left. Or chaining the commands:
s.replace('\n\n','\n').replace('\n\n','\n')
Just to encourage you to use regex, here are two introductory videos that I find intuitive:
• Regular Expressions (Regex) Tutorial
• Python Tutorial: re Module
s.replace('\n\n','\n').replace('\n\n','\n')
Tested on 3.6.
– evan_b
Jun 16 '17 at 5:28
I use this solution to delete empty lines and join everything together as one line:
match_p = re.sub(r'\s{2}', '', my_txt) # my_txt is text above
Same as what @NullUserException said, this is how I write it:
removedWhitespce = re.sub(r'^\s*$', '', line)