Reverse a string in Python two characters at a time (Network byte order)

PeterM picture PeterM · May 3, 2011 · Viewed 17.2k times · Source

Say you have this string:

ABCDEFGH

And you want to reverse it so that it becomes:

GHEFCDAB

What would be the most efficient / pythonic solution? I've tried a few different things but they all look horrible...

Thanks in advance!

Update:

In case anyone's interested, this wasn't for homework. I had a script that was processing data from a network capture and returning it as a string of hex bytes. The problem was the data was still in network order. Due to the way the app was written, I didn't want to go back through and try to use say socket.htons, I just wanted to reverse the string.

Unfortunately my attempts seemed so hideous, I knew there must be a better way (a more pythonic solution) - hence my question here.

Answer

Greg Hewgill picture Greg Hewgill · May 3, 2011

A concise way to do this is:

"".join(reversed([a[i:i+2] for i in range(0, len(a), 2)]))

This works by first breaking the string into pairs:

>>> [a[i:i+2] for i in range(0, len(a), 2)]
['AB', 'CD', 'EF', 'GH']

then reversing that, and finally concatenating the result back together.