[Tutor] Splitting long string into same len parts

Andre Roberge andre.roberge at gmail.com
Thu Feb 9 04:05:34 CET 2006


On 2/8/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
> On Wed, 8 Feb 2006, Victor Bouffier wrote:
>
> > 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.
>
> Hi Victor,
>
> Try using re.findall() instead of re.split().  The behavior you're seeing
> with split is perfectly logical: each pair of empty strings is being split
> by that three-character sequence.

There's a tongue-in-cheek quote that I really like:
"Sometimes you have a programming problem and it seems like the best
solution is to use regular expressions; now you have two problems."

Given that you are thinking of using "re", and that you seem to have a
working solution, I doubt this is a homework problem... so, how about
the untested:

n = 'xb1jyzqnd1eenkokqnhep6vp692qi9tmag3owzqw0sdq3zjf'
length = len(n)
o = []
for i in range(0, length, 3):
    o.append(n[i:i+3])

André


More information about the Tutor mailing list