I don't know if any module does this... but I feel compelled to say that the problem here is basically What is the most "pythonic" way to iterate over a list in chunks?, except you have strings instead of lists. But the most pythonic way there should also be the most pythonic here, I suppose, and it's a good thing if you can avoid re
. So here is the solution (not sure what you want if the string cannot be evenly divided by the number of parts; assuming you simply discard the "remainder"):
# python 3 version
def foo(string, n):
part_len = -(-len(string) // n) # same as math.ceil(len(string) / n)
return [''.join(x) for x in zip(*[iter_str] * part_len)]
Thus:
>>> s = "Hello, my name is foo"
>>> foo(s, 7)
['Hel', 'lo,', ' my', ' na', 'me ', 'is ', 'foo']
>>> foo(s, 6)
['Hell', 'o, m', 'y na', 'me i', 's fo']
Now admittedly having foo(s, 6)
return a list of length 5 is somewhat surprising. Maybe you want to raise an exception instead. If you want to keep the remainder, then use zip_longest
from itertools import zip_longest
def foo2(string, n, pad=''):
part_len = -(-len(string) // n)
return [''.join(x) for x in zip_longest(*[iter(string)] * part_len, fillvalue=pad)]
>>> foo2(s, 6)
['Hell', 'o, m', 'y na', 'me i', 's fo', 'o']
>>> foo2(s, 6, pad='?')
['Hell', 'o, m', 'y na', 'me i', 's fo', 'o???']