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


Question

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

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

I want to do something like the following:

for line in inputString:
    doStuff()
1
255
6/2/2016 8:37:23 PM

Accepted Answer

inputString.splitlines()

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

385
4/28/2016 9:55:16 PM

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']

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon