Split Multi-Line String into Multiple Lines



A string is a collection of characters that may be used to represent a single word or an entire phrase. Strings are useful in Python since they don't need to be declared explicitly and may be defined with or without a specifier.

In this article, we are going to find out how to split a multi-line string into multiple lines in Python.

While working with the strings in programs, we will come across multi-line strings. To process such strings one by one, we need to split the string into individual lines. In this article, we will explore different methods.

Using Python str.split() Method

The first approach is by using the Python str.split() method. Here, the split() method is used to split the string at every newline character. It returns a list where each item corresponds to a line from the original string.

Syntax

Following is the syntax of the Python str.split() method -

str.split(separator, maxsplit)

Example

Let's look at the following example, where we are going to split the multi-line string into a list of lines using the newline ('\n') character.

str1 = """Hello,
Welcome to the TutorialsPoint.
The best E-way learning."""
result = str1.split('\n')
print(result)

The output of the above program is as follows -

['Hello,', 'Welcome to the TutorialsPoint.', 'The best E-way learning.']

Using Python splitlines() Method

The second approach is by using the Python splitlines() method. It is used to split the string at various newline characters (\n, \r, \v etc.). It is more determined than split('\n\) as it handles all the common line breaks across various platforms.

Syntax

Following is the syntax of the Python str.split() method -

str.splitlines()

Example

In the following example, we are going to split the multi-line string into lines by using the built-in splitlines() method.

str1 = "Welcome\nto\nTutorialspoint"
print(str1.splitlines())

The following is the output of the above program -

['Welcome', 'to', 'Tutorialspoint']

Using Python Regular Expressions

In this approach, we are going to use the Python regular expression, Here we are going to use the regex pattern '\r?\n|\r ' that matches all the newline formats (\n, \r\n, and \r).

Example

Consider the following example, where we are going to use the regex pattern to split a string.

import re
str1 = "Ciaz\nCruze\r\nCiaz\rChiron"
result = re.split(r'\r?\n|\r', str1)
print(result)

The following is the output of the above program -

['Ciaz', 'Cruze', 'Ciaz', 'Chiron']
Updated on: 2025-05-20T10:54:47+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started