Search code examples
pythonstringtuples

Split a string to even sized chunks


How would I be able to take a string like 'aaaaaaaaaaaaaaaaaaaaaaa' and split it into 4 length tuples like (aaaa,aaaa,aaaa)


Solution

  • Use textwrap.wrap:

    >>> import textwrap
    >>> s = 'aaaaaaaaaaaaaaaaaaaaaaa'
    >>> textwrap.wrap(s, 4)
    ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa']