How do I split a 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. When working with multi-line strings in Python, you often need to split them into individual lines for processing. This article explores three effective methods to accomplish this task.

Using str.split() Method

The str.split() method is the most straightforward approach. It splits the string at every newline character ('\n') and returns a list where each item corresponds to a line from the original string.

Syntax

str.split(separator, maxsplit)

Example

Let's split a multi-line string using the newline character as the separator ?

text = """Hello,
Welcome to TutorialsPoint.
The best E-way learning."""

result = text.split('\n')
print(result)
['Hello,', 'Welcome to TutorialsPoint.', 'The best E-way learning.']

Using splitlines() Method

The splitlines() method is more robust than split('\n') as it handles various newline characters (\n, \r, \r\n, \v, etc.) across different platforms automatically.

Syntax

str.splitlines([keepends])

Example

Here's how to use splitlines() to split a multi-line string ?

text = "Welcome\nto\nTutorialsPoint"
result = text.splitlines()
print(result)
['Welcome', 'to', 'TutorialsPoint']

Using Regular Expressions

For complex scenarios, regular expressions provide maximum flexibility. The pattern r'\r?\n|\r' matches all common newline formats (\n, \r\n, and \r).

Example

Using regex to handle mixed newline formats ?

import re

text = "Ciaz\nCruze\r\nAccord\rCamry"
result = re.split(r'\r?\n|\r', text)
print(result)
['Ciaz', 'Cruze', 'Accord', 'Camry']

Comparison

Method Handles All Newlines? Best For
split('\n') No (only \n) Simple cases with \n only
splitlines() Yes Most general use cases
Regular Expressions Yes (customizable) Complex patterns or custom logic

Conclusion

Use splitlines() for most cases as it handles all newline formats automatically. Use split('\n') for simple scenarios and regular expressions when you need custom splitting patterns.

Updated on: 2026-03-24T16:49:02+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements