1

Let's say I have a list such as:

lst = ["Line1\r\nLine2\r\n", "Line3\r\nLine4\r\n", etc.]

Is there a nice pythonic way to split up the elements at the line endings and make them separate elements, ie

new_lst = ["Line1\r\n", "Line2\r\n", "Line3\r\n", "Line4\r\n"]

I know I could have a few extra lines of code to loop through the list, split up the elements and store them in a new list, but I'm relatively new to python and want to get in the habit of making use of all the cool features such as list comprehensions. Thanks in advance!

Jon Martin
  • 3,252
  • 5
  • 29
  • 45
  • Do you really need to keep the `\r\n`? Cause the Python `str.split()` method will remove it while splitting. – Wolph May 25 '12 at 13:31
  • I realize that, but I don't think it's a big deal to just have str.split("\r\n")[0] + "\r\n" or something. – Jon Martin May 25 '12 at 13:33

4 Answers4

10
>>> lst = ["Line1\r\nLine2\r\n", "Line3\r\nLine4\r\n"]
>>> new_lst = [elem for l in lst for elem in l.splitlines(True)]
>>> new_lst
['Line1\r\n', 'Line2\r\n', 'Line3\r\n', 'Line4\r\n']
Christian Witts
  • 11,375
  • 1
  • 33
  • 46
6
import itertools as it
list(it.chain(*(elem.splitlines(True) for elem in lst)))

or

[line for elem in lst for line in elem.splitlines(True)]

both return: ['Line1\r\n', 'Line2\r\n', 'Line3\r\n', 'Line4\r\n']

from doc:

S.splitlines([keepends]) -> list of strings

Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.

This works for \r\n as well as for \r and \n.

eumiro
  • 207,213
  • 34
  • 299
  • 261
0
new_lst = [x + '\r\n' for x in ''.join(lst).split('\r\n')][:-1]
dbf
  • 6,399
  • 2
  • 38
  • 65
0

For completeness, let's add this ugly solution ;)

new_lst = ('\r\n'.join(lst)).splitlines(True)
Wolph
  • 78,177
  • 11
  • 137
  • 148