Partitioning a string based on a search term in Python? -


given string:

x = 'foo test1 test1 foo test2 foo'   

i want partition string foo, along lines of:

['foo', 'test1 test1 foo', 'test2 foo'] (preferred)                   or  [['foo'], ['test1', 'test1', 'foo'], ['test2', 'foo']]  (not preferred, workable) 

i've tried itertools.groupby:

in [1209]: [list(v) _, v in itertools.groupby(x.split(), lambda k: k != 'foo')] out[1209]: [['foo'], ['test1', 'test1'], ['foo'], ['test2'], ['foo']] 

but doesn't give me i'm looking for. know use loop , this:

in [1210]: l = [[]]       ...: 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 isn't efficient leaves empty list @ end. there simpler way?

i want retain delimiter.

maybe not prettiest approach, concise , straightfoward:

[part + 'foo' part in g.split('foo')][:-1] 

output:

['foo', ' test1 test1 foo', ' test2 foo'] 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -