Remove the empty lines from a String in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Remove the empty lines from a String in Python
  2. Remove the empty lines with or without whitespace from a String
  3. Remove the empty lines from a String using str.join() with \n

# Remove the empty lines from a String in Python

To remove the empty lines from a string:

  1. Use the str.splitlines() method to split the string on newline characters.
  2. Use a list comprehension to iterate over the list.
  3. Exclude the empty lines from the result.
  4. Use the str.join() method to join the list with os.linesep as the separator.
main.py
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 ] ) # First line # Second line # Third line print(without_empty_lines)

remove empty lines from string

The code for this article is available on GitHub

The str.splitlines method splits the string on newline characters and returns a list containing the lines in the string.

main.py
multiline_string = """\ First line Second line Third line """ # ๐Ÿ‘‡๏ธ ['First line', '', 'Second line', '', 'Third line', '', ''] print(multiline_string.splitlines())

We used a list comprehension to iterate over the list of lines.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current line is truthy to exclude empty strings from the result.

The last step is to use the str.join() method to join the filtered list.

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

We used os.linesep as the separator.

The os.linesep attribute returns the string used to separate lines on the current platform.

For example \n on Unix and \r\n on Windows.

I'm on Linux, so this is the output of os.linesep for me.

main.py
import os print(repr(os.linesep)) # ๐Ÿ‘‰๏ธ '\n'
If you want to handle the scenario where the empty lines might contain only whitespace, use the str.strip() method.

# Remove the empty lines with or without whitespace from a String

If you need to remove the empty lines that may or may not contain whitespace:

  1. Use the str.splitlines() method to split the string on newline characters.
  2. Use a list comprehension to iterate over the list.
  3. Use the str.strip() method to filter out empty lines that may contain whitespace.
  4. Use the str.join() method to join the list with a newline character separator.
main.py
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() != '' ]) # First line # Second line # Third line print(without_empty_lines)

remove empty lines with or without whitespace from string

The code for this article is available on GitHub
If the empty lines in the multiline string contain only whitespace characters, we can use the str.strip() method to remove the whitespace and compare the result to an empty string.

Here is an example of calling str.splitlines() on a multiline string where some of the empty lines contain only whitespace characters.

main.py
multiline_string = """\ First line Second line Third line """ # ๐Ÿ‘‡๏ธ ['First line', ' ', 'Second line', ' ', 'Third line', ' ', ''] print(multiline_string.splitlines())

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

If the line is equal to an empty string once the leading and trailing whitespace is removed, we consider it to be an empty line.

Alternatively, you can use the str.join() method with a newline character to avoid an extra import.

# Remove the empty lines from a String using str.join() with \n

This is a four-step process:

  1. Use the str.splitlines() method to split the string on newline characters.
  2. Use a list comprehension to iterate over the list.
  3. Exclude the empty lines from the result.
  4. Use the str.join() method to join the filtered list with \n as the separator.
main.py
multiline_string = """\ First line Second line Third line """ without_empty_lines = '\n'.join([ line for line in multiline_string.splitlines() if line ]) # First line # Second line # Third line print(without_empty_lines)

remove empty lines from string using str join with n

The code for this article is available on GitHub

We used the \n (newline) character as the separator in the example to not have to import the os module.

However, note that this approach doesn't handle the scenario where the lines in the multiline string are separated by another character, e.g. \r\n\ (Windows).

For a solution that is consistent between operating systems, stick to the os.linesep attribute.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev