[Tutor] Splitting long string into same len parts

Victor Bouffier victor at grupocdm.com
Thu Feb 9 02:46:26 CET 2006


Hi to all,

I'd like to split a long string into equally long strings (len(str) =
3). I did the following using regexes:

>>> n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf'
>>> o = re.split(r'(...)', n)
>>> print o
['', 'xb1', '', 'jyz', '', 'qnd', '', '1ee', '', 'nko', '', 'kqn', '',
'hep', '', '6vp', '', '692', '', 'qi9', '', 'tma', '', 'g3o', '', 'wzq',
'', 'w0s', '', 'dq3', '', 'zjf', '']

Which gives me empty strings between each value. So to actually have
this working I ended up filtering through a list comprehension:

>>> o = [ x for x in re.split(r'(...)', n) if x ]
>>> print o
['xb1', 'jyz', 'qnd', '1ee', 'nko', 'kqn', 'hep', '6vp', '692', 'qi9',
'tma', 'g3o', 'wzq', 'w0s', 'dq3', 'zjf']

This is what I needed. Is there an easier or more straightforward way to
do this?

Thanks.
Victor




More information about the Tutor mailing list