How do I split a multi-line string into multiple lines?
To break apart a multi-line string into individual lines, "slice and dice" it using splitlines()
:
For line breaks represented by \n
, cut through the string using split('\n')
:
To keep line breaks in your lines list, use splitlines(True)
a.k.a the "includer":
Practical approaches and best practices
Looping through lines
Once you've a list of lines:
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')
:
Those empty lines
Facing blanks? Both splitlines()
and split('\n')
will treat blank lines as empty strings (''
):
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()
:
Wading through the Big Data
Got a fat multi-line string on your hands (like a file)? Try lazy iteration for leaner memory usage:
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!
Was this article helpful?