Python Forum
Split a string into segments
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Split a string into segments
#1
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?
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#2
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
Reply
#3
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')] >>>
Reply
#4
Thank you. Guess Ill have to read up on generators.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  doing string split with 2 or more split characters Skaperen 22 2,318 Aug-13-2023, 01:57 AM
Last Post: Skaperen
Sad How to split a String from Text Input into 40 char chunks? lastyle 7 1,054 Aug-01-2023, 09:36 AM
Last Post: Pedroski55
  [split] Parse Nested JSON String in Python mmm07 4 1,414 Mar-28-2023, 06:07 PM
Last Post: snippsat
  Split string using variable found in a list japo85 2 1,238 Jul-11-2022, 08:52 AM
Last Post: japo85
  Split string knob 2 1,841 Nov-19-2021, 10:27 AM
Last Post: ghoul
  Split string between two different delimiters, with exceptions DreamingInsanity 2 1,979 Aug-24-2020, 08:23 AM
Last Post: DreamingInsanity
  split string enigma619 1 2,029 May-20-2020, 02:47 PM
Last Post: perfringo
  Split string with multiple delimiters and keep the string in "groups" DreamingInsanity 4 6,356 May-12-2020, 09:31 AM
Last Post: DeaD_EyE
  Regex Help for clubbing similar sentence segments regstuff 3 2,113 Nov-20-2019, 06:46 AM
Last Post: perfringo
  Split a long string into other strings with no delimiters/characters krewlaz 4 2,706 Nov-15-2019, 02:48 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020