tags:

views:

6023

answers:

3

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()
A: 
for line in split(inputString, "\n"):
    doStuff()
Simon
Now, which way is correct, inputString.split(char) or split(inputString, char)?
bradtgmurray
Simon's split() comes from the String module and is deprecated. It's better to use the string object's method (inputString.split).
efotinis
Plus the OO (inputString.split()) is easier to read.
Unkwntech
+11  A: 
inputString.splitlines()

Will give you an array with each item, the splilines() function is designed to split each line into an array element.

Unkwntech
+15  A: 

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']
efotinis
This will only work on systems that use '\n' as the line terminator.
Jeremy Cantrell
@Jeremy: Triple-quoted string literals always use a '\n' EOL, regardless of platform. So do files read in text mode.
efotinis