Simon Forman schrieb:
On Aug 14, 8:22 pm, candide <cand...@free.invalid> wrote:
Suppose you need to split a string into substrings of a given size (except
possibly the last substring). I make the hypothesis the first slice is at the
end of the string.
A typical example is provided by formatting a decimal string with thousands
separator.

What is the pythonic way to do this ?

...
Thanks

FWIW:

def chunks(s, length=3):
    stop = len(s)
    start = stop - length
    while start > 0:
        yield s[start:stop]
        stop, start = start, start - length
    yield s[:stop]


s = '1234567890'
print ','.join(reversed(list(chunks(s))))
# prints '1,234,567,890'

or:

>>> def chunks(s, length=3):
        i, j = 0, len(s) % length or length
        while i < len(s):
                yield s[i:j]
                i, j = j, j + length

>>> print(','.join(list(chunks(s))))
1,234,567,890
>>> print(','.join(list(chunks(s,2))))
12,34,56,78,90
>>> print(','.join(list(chunks(s,4))))
12,3456,7890

Regards,
Gregor
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to