Returns a list of string letters grouped in two

I have a string consisting of letters and numbers, and I want a list of these grouped in two, that is, I:

shv = "abcdef"

I want too:

('ab'; 'cd', 'ef')

I can do:

thv  = (shv[0:2], shv[2:4], shv[4:6]) 

But for some reason this seems a little unviable: is there a better way, i.e. for a string on either side and with a different grouping value (for example, groups of n letters)

+3
source share
6 answers

You can use list comprehension and use the argument step 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 decided that you didn't need any incomplete pairs. You? If you just go to len(shv), I believe that you will get the remaining len(shv) % nletters 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']

( , len(shv)-(n-1).)

+5

textwrap , :

>>> import textwrap
>>>
>>> shv = "abcdef"
>>> thv = textwrap.wrap(shv, 2)
>>> thv
['ab', 'cd', 'ef']

, , :

>>> thv = textwrap.wrap(shv, 4)
>>> thb
['abcd', 'ef']

"" , :

>>> thv = [substr for substr in textwrap.wrap(shv, 4) if len(substr) == 4]
>>> thv
['abcd']
+4

What about

>>> import re
>>> re.findall("..", shv)
['ab', 'cd', 'ef']

For an arbitrary length (e.g. 3) use a quantifier {n}:

>>> shv = "abcdefghi"
>>> re.findall(".{3}", shv)
['abc', 'def', 'ghi']

If you want to use the remaining letters that do not match the whole, use {1,n}:

>>> shv = "abcdefghijk"
>>> re.findall(".{1,3}", shv)
['abc', 'def', 'ghi', 'jk']
+2
source

Nice little trick with copied iterators.

tuple(''.join(i) for i in zip(*[iter(shv)]*2))

alternative version if you feel sentimentality for a sad lonely character left at the end of a line with an odd length.

from itertools import izip_longest
tuple(''.join(i) for i in izip_longest(*[iter(shv)]*2, fillvalue=''))
+2
source

Here is a regular expression path.

import re

shv = "abcdef"
print re.findall('..',shv)
+1
source
shv = "abcdef"
[''.join(item) for item in zip(shv[0::2],shv[1::2])]
0
source

All Articles