Good use for itertools.dropwhile and itertools.takewhile
Terry Reedy
tjreedy at udel.edu
Tue Dec 4 17:21:33 EST 2012
On 12/4/2012 3:44 PM, Terry Reedy wrote:
> If the original string has no excess whitespace, description is what
> remains of s after product prefix is omitted. (Py 3 code)
>
> from itertools import takewhile
> def allcaps(word): return word == word.upper()
>
> def split_product_itertools(s):
> product = ' '.join(takewhile(allcaps, s.split()))
> return product, s[len(product)+1:]
>
> print(split_product_itertools("CAPSICUM RED fresh from QLD"))
> >>>
> ('CAPSICUM RED', 'fresh from QLD')
>
> Without that assumption, the same idea applies to the split list.
>
> def split_product_itertools(s):
> words = s.split()
> product = list(takewhile(allcaps, words))
> return ' '.join(product), ' '.join(words[len(product):])
Because these slice rather than index, either works trivially on an
empty description.
print(split_product_itertools("CAPSICUM RED"))
>>>
('CAPSICUM RED', '')
--
Terry Jan Reedy
More information about the Python-list
mailing list