Given a string:
x = 'foo test1 test1 foo test2 foo'
I want to partition the string by foo
, so that I get something along the lines of:
['foo', 'test1 test1 foo', 'test2 foo'] (preferred)
or
[['foo'], ['test1', 'test1', 'foo'], ['test2', 'foo']] (not preferred, but workable)
I've tried itertools.groupby
:
In [1209]: [list(v) for _, v in itertools.groupby(x.split(), lambda k: k != 'foo')]
Out[1209]: [['foo'], ['test1', 'test1'], ['foo'], ['test2'], ['foo']]
But it doesn't exactly give me what I'm looking for. I know I could use a loop and do this:
In [1210]: l = [[]]
...: for v in x.split():
...: l[-1].append(v)
...: if v == 'foo':
...: l.append([])
...:
In [1211]: l
Out[1211]: [['foo'], ['test1', 'test1', 'foo'], ['test2', 'foo'], []]
But it isn't very efficient leaves the empty list at the end. Is there a simpler way?
I want to retain the delimiter.