Python control order
I just noticed that none of the existing answers work if the input length is odd. Most answers lose the last character. My previous answer throws an exception.
If you just want the last character to be attached to the end, you could do something like this:
print "".join(map(lambda a,b:(b or '')+a, s[::2], s[1::2]))
or in 2.6 and later:
print "".join(b+a for a,b in izip_longest(s[::2],s[1::2], fillvalue=''))
This is based on Anthony Townes' answer, but uses either map
or izip_longest
to make sure the last character in an odd length string is not discarded. The bit (b or '')
in the version map
is to convert None
which map
pads to ''
.
source to share
Since every line is iterable in Python too, itertools comes in handy here.
In addition to the functions provided by itertools, the documentation also contains many recipes.
from itertools import izip_longest
# From Python 2.6 docs
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
Now you can use grouper to group a string into pairs, then reverse the pairs, and then concatenate them back into a string.
pairs = grouper(2, "abcdefgh")
reversed_pairs = [''.join(reversed(item)) for item in pairs]
print ''.join(reversed_pairs)
source to share