Python Split String by New Line

Python – Split String by New Line

To split a string in Python with new line as delimiter, you can use string split() method, or split() method of re(regular expression) module.

In this tutorial, you will learn how to split a string by new line character \n in Python using str.split() and re.split() methods.

Examples

1. Split string by new line using string split() method in Python

In this example, we will take a multiline string x. We will call the split() method on this string with new line character \n passed as argument. split() method splits the string by new line character and returns a list of strings.

Python Program

# Input string with multiple lines
x = """Line 1
Line 2
Line 3"""

# Split the string into lines using split()
lines = x.split("\n")

# Print each line
for line in lines:
    print(line)
Run Code Copy

Output

Line 1
Line 2
Line 3

The string can also contain \n characters in the string as shown below, instead of a multi-line string with triple quotes.

Python Program

# Input string with multiple lines
x = "Line 1\nLine 2\nLine 3"

# Split the string into lines using split()
lines = x.split("\n")

# Print each line
for line in lines:
    print(line)
Run Code Copy

2. Split string by new line using re.split() method in Python

In this example, we will split the string by new line using split() method of regular expression re package.

To use re package, we have to import it at the start of our program.

Python Program

import re

# Input string with multiple lines
x = "Line 1\nLine 2\nLine 3"

# Split the string into lines using re.split()
lines = re.split('\n', x)

# Print each line
for line in lines:
    print(line)
Run Code Copy

Output

Line 1
Line 2
Line 3

3. Split string by one or more newline characters in Python

In this example, we will take a string with substrings separated by one or more new line characters. We will use re package to split the string with one or more new line characters as delimiter. The regular expression that represents one or more new line characters is \n+. We shall pass this expression and the string as arguments to re.split() method.

The syntax of re.split() method is re.split(regular_expression, string). The function returns list of substrings split from string based on the regular_expression.

Python Program

import re

# Input string with multiple lines
x = """Line 1

Line 2



Line 3"""

# Split the string into lines
lines = re.split('\n+', x)

# Print each line
for line in lines:
    print(line)
Run Code Copy

Regular Expression \n+ represents one or more adjacent new lines. So, one or more new lines is considered as a separator between splits.

Output

Line 1
Line 2
Line 3

Summary

In this tutorial of Python Examples, we learned how to split a string by new line using String.split() and re.split() methods.

Related Tutorials

Code copied to clipboard successfully 👍