Use itertools.groupby
and group using str.isspace
:
>>> from itertools import groupby
>>> lst = ['S', 't', 'u', 'a', 'r', 't', ' ', 'S', 't', 'e', 'v', 'e', ' ', 'A', 'n', 'd', 'r', 'e', 'w', ' ', 'L', 'u', 'k', 'e', ' ', 'S', 'h', 'a', 'n', 'e', 'y', ' ', 'L', 'u', 'k', 'e', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'R', 'o', 'b', ' ']
>>> [''.join(g) for k, g in groupby(lst, key=str.isspace) if not k]
['Stuart', 'Steve', 'Andrew', 'Luke', 'Shaney', 'Luke', 'Moley', 'Moley', 'Rob']
I am reading from a text file. I broke up the text and placed it into
a list, I'm now wondering how to get it so it recognizes when a space
is present and it concatenates the data accordingly. I'm not sure how
though
I am not sure how you read this text, but you're processing it incorrectly. Don't call list()
on the line or the whole text you've read from the file:
>>> s = 'Stuart Steve Andrew Luke Shaney Luke Moley Moley Rob'
>>> list(s)
['S', 't', 'u', 'a', 'r', 't', ' ', 'S', 't', 'e', 'v', 'e', ' ', 'A', 'n', 'd', 'r', 'e', 'w', ' ', 'L', 'u', 'k', 'e', ' ', 'S', 'h', 'a', 'n', 'e', 'y', ' ', 'L', 'u', 'k', 'e', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'R', 'o', 'b']
If you want a list of words simply use str.split
on the text you've read:
>>> s.split()
['Stuart', 'Steve', 'Andrew', 'Luke', 'Shaney', 'Luke', 'Moley', 'Moley', 'Rob']