Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a quick one-liner to remove empty lines from a python string?

I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this?

Note: I'm not looking for a general code re-formatter, just a quick one or two-liner.

Thanks!

like image 350
Andrew Wagner Avatar asked Jul 17 '09 00:07

Andrew Wagner


People also ask

Can you strip \n in Python?

Remove \n From the String in Python Using the str. strip() Method. In order to remove \n from the string using the str. strip() method, we need to pass \n and \t to the method, and it will return the copy of the original string after removing \n and \t from the string.

How do you delete multiple new lines in Python?

Another approach is to use the regular expression functions in Python to replace the newline characters with an empty string. The regex approach can be used to remove all the occurrences of the newlines in a given string. The re. sub() function is similar to replace() method in Python.


2 Answers

How about:

text = os.linesep.join([s for s in text.splitlines() if s]) 

where text is the string with the possible extraneous lines?

like image 135
Lawrence Johnston Avatar answered Sep 24 '22 12:09

Lawrence Johnston


"\n".join([s for s in code.split("\n") if s]) 

Edit2:

text = "".join([s for s in code.splitlines(True) if s.strip("\r\n")]) 

I think that's my final version. It should work well even with code mixing line endings. I don't think that line with spaces should be considered empty, but if so then simple s.strip() will do instead.

like image 34
Wojciech Bederski Avatar answered Sep 23 '22 12:09

Wojciech Bederski