Well, you can use itertools
module to group items according the fact they are space or not.
For instance, you can use str.ispace
function as a predicate to group the items:
list1 = ["I", "am", "happy", " ", "and", "fine", " ", "and", "good"]
for key, group in itertools.groupby(list1, key=str.isspace):
print(key, list(group))
You get:
False ['I', 'am', 'happy']
True [' ']
False ['and', 'fine']
True [' ']
False ['and', 'good']
Based on that, you can construct a list by excluding the groups which key is True
(isspace
returned True
):
result = [list(group)
for key, group in itertools.groupby(list1, key=str.isspace)
if not key]
print(result)
You get this list of lists:
[['I', 'am', 'happy'], ['and', 'fine'], ['and', 'good']]
If you are not familiar with comprehension lists, you can use a loop:
result = []
for key, group in itertools.groupby(list1, key=str.isspace):
if not key:
result.append(list(group))
You can unpack this result to 3 variables:
sublist1, sublist2, sublist3 = result