Reputation: 3392
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
Reputation: 80111
For completeness, let's add this ugly solution ;)
new_lst = ('\r\n'.join(lst)).splitlines(True)
Upvotes: 0
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
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