How to remove empty lines with or without whitespace in Python

后端 未结 10 2443
感动是毒
感动是毒 2020-12-01 07:42

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:
          


        
相关标签:
10条回答
  • 2020-12-01 07:48

    Same as what @NullUserException said, this is how I write it:

    removedWhitespce = re.sub(r'^\s*$', '', line)
    
    0 讨论(0)
  • 2020-12-01 07:53

    you can simply use rstrip:

        for stuff in largestring:
            print(stuff.rstrip("\n")
    
    0 讨论(0)
  • 2020-12-01 07:55

    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
    
    >>> 
    
    0 讨论(0)
  • 2020-12-01 07:56

    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

    0 讨论(0)
  • 2020-12-01 07:58

    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()])
    
    0 讨论(0)
  • 2020-12-01 08:01

    My version:

    while '' in all_lines:
        all_lines.pop(all_lines.index(''))
    
    0 讨论(0)
提交回复
热议问题