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!
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.
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.
How about:
text = os.linesep.join([s for s in text.splitlines() if s])
where text
is the string with the possible extraneous lines?
"\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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With