[Tutor] Output of list

Martin Walsh mwalsh at groktech.org
Sun Dec 23 21:53:43 CET 2007


János Juhász wrote:
> Dear Marty,

Hi Janos,

>> ... Or, by extending Alan's solution ...
>>
>> def splitStringByN(s, n):
>>    for m in range(0, len(s), n):
>>        yield s[m:m+n]
>>
>> k = 'abcdefghi'
>> list(splitStringByN(k, 2))
> 
> It seems to be the most readable solution for me.

For completeness, one could also pull it out of the function def and use
a generator expression directly. If I'm not mistaken, this would be more
or less equivalent:

k = 'abcdefghi'
list((k[m:m+2] for m in range(0, len(k), 2)))

> 
> 
>> As it turns out, this is similar to an ASPN Cookbook recipe contributed
>> by Dmitry Vasiliev:
>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302069
>>
>> HTH,
>> Marty
> 
> Thanks for the link.

No problem.

Happy Holidays!
Marty


More information about the Tutor mailing list