Lambda question

John Posner jjposner at codicesoftware.com
Sun Jun 5 10:29:40 EDT 2011


On 2:59 PM, Ian Kelly wrote:
> On Sat, Jun 4, 2011 at 12:09 PM, Chris Angelico <rosuav at gmail.com> wrote:
>> Python doesn't seem to have an inbuilt function to divide strings in
>> this way. At least, I can't find it (except the special case where n
>> is 1, which is simply 'list(string)'). Pike allows you to use the
>> division operator: "Hello, world!"/3 is an array of 3-character
>> strings. If there's anything in Python to do the same, I'm sure
>> someone else will point it out.
> Not strictly built-in, but using the "grouper" recipe from the
> itertools docs, one could do this:
>
> def strsection(x, n):
>     return map(''.join, grouper(n, x, ''))

As Ian discovered, the doc string for grouper() [on page
http://docs.python.org/library/itertools.html] is wrong:

    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"

grouper() doesn't return a string directly -- hence the need for
"map('', join ..."

Here's another implementation:

    def group(stg, count):
        return [ stg[n:n+count] for n in range(len(stg)) if n%count==0 ]

    print group('abcdefghij', 3)      # ['abc', 'def', 'ghi', 'j']
    print group('abcdefghijk' * 2, 7) # ['abcdefg', 'hijkabc',
    'defghij', 'k']
    print group('', 42)               # []


-John


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110605/b43a98a3/attachment.html>


More information about the Python-list mailing list