[Tutor] Output of list

János Juhász janos.juhasz at VELUX.com
Sun Dec 23 17:52:28 CET 2007

Dear Emil,

> I want to be capable of converting a string into a list where all 
> the items, in  the list, have a fixed length not equal to 1 e.g i 
> have k = 'abcdefgh' and I want the fixed length for all the the 
> items to be 2 then the list would look like ['ab', 'cd', 'ef, 'gh'].
> How do i do this?

> - Emil

It is nice place to use a generator:

def pairs(sliceit):
    streamlist = list(sliceit)
    while streamlist:
        pair = streamlist.pop() 
        try:    pair += streamlist.pop()
        except: pass
        yield pair

## Probably it is easier to understand
def pairs2(sliceit):
        while sliceit:
            yield sliceit[:2]
            sliceit = sliceit[2:]
    except: # oops, it was odd length
        yield sliceit

print '_'.join(e for e in pairs('abcd'))
print '_'.join(e for e in pairs('abcde'))
print '_'.join(e for e in pairs2('abcd'))
print '_'.join(e for e in pairs2('abcde'))

Best Regards,

More information about the Tutor mailing list