How to remove empty lines from a list item (i.e., not an empty list item itself)

Example:

[<tr class="sample"> <td> <tr> </tr> <td id="ess8key-8">TEXTEXTEXTEXTEXTEX</td> <td class="sample-class" id="sample-id-8">TEXTEXTEXTEXTEXTEX</td> </tr> <tr> </tr> </td> </tr>, <tr class="sample"> <td> <tr> <td colspan="2"><strong>TITLE:</strong></td> </tr> <tr> <td class="sample-class" id="sample-id-1">TEXTEXTEXTEXTEXTEX</td> <td> </td> </tr>] 

desired:

 [<tr class="sample"> <td> <tr> </tr> <td id="ess8key-8">TEXTEXTEXTEXTEXTEX</td> <td class="sample-class" id="sample-id-8">TEXTEXTEXTEXTEXTEX</td> </tr> <tr> </tr> </td> </tr>, <tr class="sample"> <td> <tr> <td colspan="2"><strong>TITLE:</strong></td> </tr> <tr> <td class="sample-class" id="sample-id-1">TEXTEXTEXTEXTEXTEX</td> <td> </td> </tr>] 

    2 answers 2

    With regulars:

     import re p = re.compile('\n{2,}') oldtext = ''' adsffgsf fsafds fdsafsf adfsfas sdfasf''' newtext = p.sub('\n', oldtext) # newtext = p.sub('\n', oldtext).strip('\n') - если в начале конце тоже не должно быть пустых строк print (newtext) 
    • one
      Blank lines at the beginning and end will remain. But this can be solved with the help of "\n blabla \n".strip("\n") . - pank
    • @pank I thought that the empty line at the beginning / end may be a "special" case, and so you are right. - andy.37
    • And what does this line mean? p = re.compile('\n{2,}') - C. Anon
    • one
      @ C.Anon - compiled regular expression. A line break that occurs 2 or more times in a row. By the way, the string consisting of spaces is not considered empty. - andy.37
    • @ andy.37 Wouldn't it be better if \s instead of \n ? - C. Anon

    So you can remove empty lines from one line:

     s1 = """ Ваш текст с пустыми строками """ s2 = "\n".join(filter(bool, s1.splitlines())) # Удаляем пустые строки 

    And from each list item:

     a1 = [s1, s1 + "last line"] # массив строк # удаляем пустые строки из элементов массива a2 = list(map(lambda x: "\n".join(filter(bool, x.splitlines())), a1))