Jon Martin
Jon Martin

Reputation: 3392

Split up element in a list in python

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!

Upvotes: 1

Views: 887

Answers (4)

Wolph
Wolph

Reputation: 80111

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

new_lst = ('\r\n'.join(lst)).splitlines(True)

Upvotes: 0

Christian Witts
Christian Witts

Reputation: 11585

>>> 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']

Upvotes: 10

dbf
dbf

Reputation: 6499

new_lst = [x + '\r\n' for x in ''.join(lst).split('\r\n')][:-1]

Upvotes: 0

eumiro
eumiro

Reputation: 213085

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.

Upvotes: 6

Related Questions