Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string separated by "\r\n" into a list of lines?

Tags:

python

string

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?

like image 996
ahhtwer Avatar asked Jul 27 '10 15:07

ahhtwer


People also ask

How do I split a string into a list in r?

To split a string in R, use the strsplit() method. The strsplit() is a built-in R function that splits the string vector into sub-strings. The strsplit() method returns the list, where each list item resembles the item of input that has been split.

How do you split a string into a list of elements?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a string into lines in Python?

To split the line in Python, use the String split() method. The split() is an inbuilt method that returns a list of lines after breaking the given string by the specified separator. In this tutorial, the line is equal to the string because there is no concept of a line in Python. So you can think of a line as a string.


2 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 "\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'] 
like image 128
Dave Kirby Avatar answered Oct 04 '22 01:10

Dave Kirby


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

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

like image 42
wshato Avatar answered Oct 03 '22 23:10

wshato