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
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
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']
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