How to remove empty lines with or without whitespace in Python

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

提交回复
热议问题