How to remove empty lines with or without whitespace in Python

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

    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']
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 08:09
    lines = bigstring.split('\n')
    lines = [line for line in lines if line.strip()]
    
    0 讨论(0)
  • 2020-12-01 08:13

    I use this solution to delete empty lines and join everything together as one line:

    match_p = re.sub(r'\s{2}', '', my_txt) # my_txt is text above
    
    0 讨论(0)
提交回复
热议问题