How to remove empty lines with or without whitespace in Python

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

    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.

提交回复
热议问题