Skip to main content

How to Remove Empty Lines from Strings in Python

Removing empty lines from a multiline string is a common text processing task in Python.

This guide explores how to effectively remove both empty lines and lines containing only whitespace, using splitlines(), strip(), list comprehensions, and join().

Removing Empty Lines with splitlines() and List Comprehension

The most Pythonic way to remove empty lines from a string involves combining splitlines() with a list comprehension:

import os

multiline_string = """\
First line

Second line

Third line


"""

without_empty_lines = os.linesep.join(
[line for line in multiline_string.splitlines() if line]
)

print(without_empty_lines)

Output:

First line
Second line
Third line
  • multiline_string.splitlines() splits the string into a list of lines, handling different line endings (\n, \r, \r\n) correctly.
  • [line for line in ... if line] is a list comprehension. It iterates through the lines and keeps only the truthy ones. Empty strings are falsy, so they are excluded.
  • os.linesep.join(...) joins the filtered lines back into a single string, using the operating system's correct line separator (\n on Linux/macOS, \r\n on Windows). This makes the code cross-platform.

Handling Lines with Whitespace

The previous example removes lines that are completely empty. If lines might contain spaces, tabs, or other whitespace, you need to use strip() to remove them before checking for emptiness:

import os

multiline_string = """\
First line

Second line

Third line


"""

without_empty_lines = os.linesep.join([
line for line in multiline_string.splitlines()
if line.strip() != ''
])

print(without_empty_lines)

Output:

First line
Second line
Third line
  • The line.strip() != '' is used to check for empty lines, and empty lines that contain whitespace, since after removing leading/trailing whitespace it is an empty string.

Using join() with \n (Cross-Platform Considerations)

You can use '\n'.join(...) instead of os.linesep.join(...). However, os.linesep is the most portable and correct approach, as it automatically uses the correct line separator for the current operating system:

multiline_string = """\
First line

Second line

Third line


"""

without_empty_lines = '\n'.join([
line for line in multiline_string.splitlines()
if line
])
print(without_empty_lines)

Output:

First line
Second line
Third line
  • This will work on Linux and macOS, but it might have some issues with line separators on Windows, where the standard line separator is \r\n.