Take the 2-minute tour ×

I am reading in some data from the subprocess module's communicate method. It is coming in as a large string separated by "\r\n"s. I want to split this into a list of lines. How is this performed in python?

share|improve this question
When you read up on string.split() what did you find? What have you tried? What tutorial are you using? –  S.Lott Jul 27 '10 at 15:10
add comment

3 Answers

up vote 12 down vote accepted

Use the splitlines method on the string.

From the docs:

str.splitlines([keepends]) Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

This will do the right thing whether the line endings are "\r\n", "\r" or "\n" regardless of the OS.

NB a line ending of "\n\r" will also split, but you will get an empty string between each line since it will consider "\n" as a valid line ending and "\r" as the ending of the next line. e.g.

>>> "foo\n\rbar".splitlines()
['foo', '', 'bar']
share|improve this answer
add comment

Check out the doc for string methods. In particular the split method.


share|improve this answer
add comment
s = re.split(r"[~\r\n]+", string_to_split)

This will give you a list of strings in s.

share|improve this answer
Although, if you think 'a\n\nb' should be split into three strings ('a', '', and 'b'), this will fail. –  Chris B. Jul 27 '10 at 15:22
That's true, this will ignore blank lines. –  tkerwin Jul 27 '10 at 15:29
add comment

Your Answer


