Welcome, guest | Sign In | My Account | Store | Cart

I needed to chunk up some text to send over UDP and didn't want to have messy for loops with an if condition for size and then the little bit left over. All that struck me as very messy. I then thought of the re module and came up with a very simple solution to chunk up data.

Python, 9 lines
1
2
3
4
5
6
7
8
9
import re

def chunker(data, size):
    m = re.compile(r'.{%s}|.+' % str(size),re.S)
    return m.findall(data)

if __name__ == "__main__":
    t = 'some sample text is all that i want'
    chunker(t, 10)

sample output:

` python chunker.py

['some sampl', 'e text is ', 'all that i', ' want']