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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)