Given the following:
# from : https://stackoverflow.com/company
s = """
Founded in 2008, Stack Overflow’s public platform is used by nearly everyone who codes comes to learn, share their knowledge, collaborate, and build their careers.
Our products and tools help developers and technologists in life and at work. These products include Stack Overflow for Teams, Stack Overflow Advertising, and Stack Overflow for Talent and Jobs.
Stack Overflow for Teams, our core SaaS collaboration product, is helping thousands of companies around the world as the transition to remote work, address business continuity challenges, and undergo digital transformation.
Whether it’s on Stack Overflow or within Stack Overflow for Teams, community is at the center of all that we do.
"""
list_to_split = s.split()
I'd like to split it into lists where each list has at most m
characters.
Here's an attempt:
# max list char count
m = 50
count = 0
indices = [0]
for i, el in enumerate(list_to_split):
count += len(str(el))
if count >= max_chars:
indices.append(i)
count = 0
split_lists = [list_to_split[s[0] : s[1]] for s in zip(indices[:-1], indices[1:])]
# check
flat = list(itertools.chain.from_iterable(split_lists))
flat == list_to_split
This returns False
.
The elements which aren't in flat
but are in list_to_split
are
['that', 'we', 'do.']
Ordering is very important for this (it should be in the same order as given) - and no data can be lost.
edit
whoever flagged this as a duplicate of this (Split string every nth character?) clearly didn't read both.