Explain Codes LogoExplain Codes Logo

How do I split a multi-line string into multiple lines?

python
string-manipulation
best-practices
performance
Nikita BarsukovbyNikita Barsukov·Feb 13, 2025
TLDR

To break apart a multi-line string into individual lines, "slice and dice" it using splitlines():

lines = "Line 1\nLine 2\nLine 3".splitlines()

For line breaks represented by \n, cut through the string using split('\n'):

lines = "Line 1\nLine 2\nLine 3".split('\n')

To keep line breaks in your lines list, use splitlines(True) a.k.a the "includer":

lines = "Line 1\nLine 2\nLine 3".splitlines(True)

Practical approaches and best practices

Looping through lines

Once you've a list of lines:

for line in lines: process(line) # Feel free to replace `process` with your magic function (🎩🐇)

Where split('\n') shines

split('\n') gains the upper hand in scenarios where you're detecting a specific delimiter, e.g., logs or unique format files. Let's call it the "precision slicer".

Retaining line breaks

splitlines(True) helps when you want to hang on to line break characters after splitting. Handy when you want your file to look just as pretty when you put it back together after some line-level processing.

Stay clear of deprecated methods

Skip the old timers from the string module, stick with str methods, because we like our code like our news - fresh and updated.

Handling peculiar situations

Keeping trailing white spaces

splitlines() might give a cold shoulder to trailing white spaces. To embrace every space, stick to split('\n'):

line_with_space = "Line 1 \nLine 2\n".split('\n')

Those empty lines

Facing blanks? Both splitlines() and split('\n') will treat blank lines as empty strings (''):

empty_lines = "Line 1\n\nLine 3".splitlines()

New-age line breaks

These days, we get \r or \r\n as line breaks. splitlines() is the one-size-fits-all here - ready to handle just about any line break type flung at it.

Advanced splitting techniques

The regular expression way

Got a complex situation? Multiple delimiters? Fear not! The re module has got your back with re.split():

import re lines = re.split(r'\n|\r\n|\r', multi_line_string)

Wading through the Big Data

Got a fat multi-line string on your hands (like a file)? Try lazy iteration for leaner memory usage:

for line in iter(multi_line_string.splitlines()): process(line) # Remember, don't process too hard. 😅

Prepping the string

To prep a string before splitting, remember to handle with care, or risk changing the very data you're about to slice and dice!