Splitting a string separated by "rn" into a list of lines?

Question:

I am reading in some data from the subprocess module’s communicate method. It is coming in as a large string separated by “rn”s. I want to split this into a list of lines. How is this performed in python?

Asked By: ahhtwer

||

Answers:

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 “rn”, “r” or “n” regardless of the OS.

NB a line ending of “nr” 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.

>>> "foonrbar".splitlines()
['foo', '', 'bar']
Answered By: Dave Kirby
s = re.split(r"[~rn]+", string_to_split)

This will give you a list of strings in s.

Answered By: tkerwin

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

http://docs.python.org/library/stdtypes.html#string-methods

Answered By: wshato
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.