10
votes

I have a string, which I need to split into 2-letter pieces. For example, 'ABCDXY' should become ['AB', 'CD', 'XY']. The behavior in the case of odd number of characters may be entirely arbitrary (I'll check the length in advance).

Is there any way to do this without an ugly loop?

6
Hey mate... what do you mean by "ugly loop"? XD - Littm
I didn't think about it. But now that I did... An ugly loop is a loop that is uglier than necessary, or that is present when no loop is really required :) - max

6 Answers

24
votes
>>> [s[i:i + 2] for i in range(0, len(s), 2)]
['AB', 'CD', 'XY']
16
votes

Using regular expressions!

>>> import re
>>> s = "ABCDXYv"
>>> re.findall(r'.{1,2}',s,re.DOTALL)
['AB', 'CD', 'XY', 'v']

I know it has been a while, but I came back to this and was curious about which method was better; mine: r'.{1,2}' or Jon's r'..?'. On the surface, Jon's looks much nicer, and I thought it would be much faster than mine, but I was surprised to find otherwise, so I thought I would share:

>>> import timeit
>>> timeit.Timer("re.findall(r'.{1,2}', 'ABCDXYv')", setup='import re').repeat()
[1.9064299485802252, 1.8369554649334674, 1.8548105833383772]
>>> timeit.Timer("re.findall(r'..?', 'ABCDXYv')", setup='import re').repeat()
[1.9142223469651611, 1.8670038395145383, 1.85781945659771]

Which shows that indeed r'.{1,2}' is the better/faster choice. (But only slightly)

2
votes

You could try:

s = 'ABCDEFG'
r = [s[i:i+2] for i in xrange(0, len(s), 2)]

# r is ['AB', 'CD', 'EF', 'G']

UPDATE 2

If you don't care about odd chars, you could use a regex (avoiding the loop):

s = 'ABCDEFG'
r = re.compile('(..)').findall(s)
# r is ['AB', 'CD', 'EF']
1
votes

There's nothing ugly about the perfectly Pythonic:

string = 'ABCDXY'
[string[i:i+2] for i in xrange(0, len(string), 2)]

You could also use the following (from - http://docs.python.org/library/itertools.html):

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

(Which depending how you look at it - may or may not be using 'loops' ;))

or something like:

re.findall('..?', string)
0
votes

Yet another solution, this one built on zip and a slice stride:

map(''.join, itertools.izip_longest(mystr[::2], mystr[1::2], fillvalue=''))

It does handle odd-length inputs.

0
votes

Here's a yet another solution without explicit loops (though @Emmanuel's answer is the most appropriate for your question):

s = 'abcdef'
L = zip(s[::2], s[1::2])
# -> [('a', 'b'), ('c', 'd'), ('e', 'f')]

To get strings:

print map(''.join, L)
# ['ab', 'cd', 'ef']

On Python 3 wrap using list() where necessary.