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?
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.
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.
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.
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']
Check out the doc for string methods. In particular the split method.
http://docs.python.org/library/stdtypes.html#string-methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With