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

Andrew Wagner picture Andrew Wagner · Jul 17, 2009 · Viewed 72.7k times · Source

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!

Answer

Lawrence Johnston picture Lawrence Johnston · Jul 17, 2009

How about:

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

where text is the string with the possible extraneous lines?