How to remove empty lines with or without whitespace in Python

后端 未结 10 2454
感动是毒
感动是毒 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: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
    
    >>> 
    

提交回复
热议问题