Python Forum

Full Version: Split a string into segments
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I would like to take a string and divide it into segments and came across this 'recipe' in the docs for zip_longest. However, I'm not getting the output I was expecting, which would be something like: abc def ghi

from itertools import zip_longest


def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n

    return zip_longest(*args, fillvalue=fillvalue)


# a_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
a_str = 'abcdefghi'

a = grouper(a_str, 3)
print(a)
Instead I get:

Output:
<itertools.zip_longest object at 0x000002094F398CC8>
Am I missing something here?
Code return a generator object,so use list(a).
Calling next() then the generator is exhausted until StopIteration.
>>> next(a)
('a', 'b', 'c')
>>> next(a)
('d', 'e', 'f')
>>> next(a)
('g', 'h', 'i')
>>> next(a)
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
StopIteration
it will produce iterator, so convert it to list or iterate over it elements
print(list(a))
Output:
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')] >>>
Thank you. Guess Ill have to read up on generators.