Return a list of string letters grouped by two

python

Solution

You can use a list comprehension and utilize the `step` argument of `range`:

[shv[i:i+2] for i in range(0, len(shv)-1, 2)]

For arbitrary `n`:

def my_awesome_grouping_function(shv, n):
    return [shv[i:i+n] for i in range(0, len(shv)-(n-1), n)]

Demo:

>>> shv="abcdef"
>>> [shv[i:i+2] for i in range(0, len(shv)-1, 2)]
['ab', 'cd', 'ef']
>>> [shv[i:i+3] for i in range(0, len(shv)-2, 3)]
['abc', 'def']

I trimmed the upper bound because I figured you wouldn't want any trailing incomplete pairs. Do you? If you just go to `len(shv)` I believe you will get the remaining `len(shv) % n` letters in the last element.

>>> shv="abcdefgh"
>>> [shv[i:i+3] for i in range(0, len(shv), 3)]
['abc', 'def', 'gh']
>>> [shv[i:i+3] for i in range(0, len(shv)-1, 3)]
['abc', 'def', 'gh']
>>> [shv[i:i+3] for i in range(0, len(shv)-2, 3)]
['abc', 'def']

(As you see above it has to be `len(shv)-(n-1)` for the trimming to work.)

Problem

I have a string made of letters and numbers and i want a list of these grouped by two, ie I have : ``` shv = "abcdef" ``` And i want: ``` ('ab'; 'cd', 'ef') ``` I can do : ``` thv = (shv[0:2], shv[2:4], shv[4:6]) ``` But somehow this seems a little bit ungeneric : is there a better way, ie for a string with any side and with another grouping value (by groups of n letters for example)

Original source