Split text by empty line in Python

Keep reading this article if you are looking for a method to split text by empty line in Python. This tutorial will give you a few examples to display how to split text by empty lines with detailed explanations. 

Split string in Python

The split() function is used to split a string into substrings in Python. We have another tutorial explaining the function. If you need to learn or remember the function, please look at the previous article. For example:

Code:

my_str = "Learn Share IT"
 
# Split the string by the white space
# Result returns a list of substrings
my_list = my_str.split(" ")
 
print("The substrings after being splitted are", my_list)

Result:

The substrings after being split are ['Learn', 'Share', 'IT']

Split text by empty line in Python

To split text by an empty line in Python, we have to split it by two characters (\n\n) because the first character is for a new line, and the second one is for an empty line.

Use the split() function with double \n characters

To split a string by an empty line in Python, you can use the split() method and pass it the string “\n\n” as the delimiter.

Here is an example of how you can do this:

Code:

text = """Below is an example text
 
Welcome to Learn Share IT!
 
Merry Christmas"""
 
# Split the text by an empty line
paragraphs = text.split("\n\n")
 
print("The text after being split by an empty line is::\n", paragraphs)

In this example, we split the text string by two newline characters (“\n\n”) and store the resulting list of paragraphs in the paragraphs variable.

Result:

The text after being split by an empty line is:
 ['Below is an example text', 'Welcome to Learn Share IT!', 'Merry Christmas']

Use the re module

You can also use the “re” module’s split() function to split the text by an empty line. To do this, you can pass it the regular expression “\n{2,}” as the delimiter.

Code:

import re

text = """Below is an example text

Welcome to Learn Share IT!

Merry Christmas"""

# Split the text by an empty line
paragraphs = re.split("\n{2,}", text)
 
print("The text after being split by an empty line is::\n", paragraphs)

Result:

The text after being split by an empty line is:
 ['Below is an example text', 'Welcome to Learn Share IT!', 'Merry Christmas']

Summary

In summary, you can use the string split() function or the split() function from the “re” module to split text in Python. To split text by empty lines, pass at least two “\n” characters. The first character is for a new line, and the second one is for an empty line.

Leave a Reply

Your email address will not be published. Required fields are marked *