How Do I Split a Multi-Line String into Multiple Lines?

How Do I Split a Multi-Line String into Multiple Lines?

I have a multi-line string that I want to do an operation on each line, like so:

inputString = """Line 1
Line 2
Line 3"""

I want to iterate on each line:

for line in inputString:
    doStuff()
0

6 Answers

inputString.splitlines()

Will give you a list with each item, the splitlines() method is designed to split each line into a list element.

3

Like the others said:

inputString.split('\n')  # --> ['Line 1', 'Line 2', 'Line 3']

This is identical to the above, but the string module's functions are deprecated and should be avoided:

import string
string.split(inputString, '\n')  # --> ['Line 1', 'Line 2', 'Line 3']

Alternatively, if you want each line to include the break sequence (CR,LF,CRLF), use the splitlines method with a True argument:

inputString.splitlines(True)  # --> ['Line 1\n', 'Line 2\n', 'Line 3']
7

Use inputString.splitlines().


Why splitlines is better

splitlines handles newlines properly, unlike split.

It also can optionally return the newline character in the split result when called with a True argument, which is useful in some specific scenarios.


Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.