how to split a string (or sequence) into pairs of characters?

Ken Seehof kseehof at neuralintegrator.com
Thu Aug 15 20:25:46 CEST 2002


> I have a segment of code that seems particularly ugly.  I want to take a
> sequence and divide it into pairs such that pairs( 'aabbccdd' ) == (
> 'aa','bb','cc','dd' ). Here's code that does what I want.
>
>   even = range( 0, len( s ), 2 )
>   odd = range( 1, len( s ), 2 )
>   even = map( s.__getitem__, even )
>   odd = map( s.__getitem__, odd )
>   pairs = map( operator.add, even, odd )
>
> I'd like it to be more elegant and more efficient, and I'd like to avoid
> using loops.  I could obviously do:
>
>   pairs = []
>   for i in range( 0,len(s),2 ):
>     pairs.append( s[i:i+2] )
>
> But even that seems a bit inefficient, and doesn't take advantages of the
> powerful sequence operations of Python.
>
> Can anyone come up with a better way of performing these operations? Extra
> kudos if it easily extends to any sublength and not just pairs.
>
> Jason


def chop(s, chunk):
    return [s[i*chunk:(i+1)*chunk] for i in range((len(s)+chunk-1)/chunk)]

- Ken





More information about the Python-list mailing list