Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 582
PeterM Avatar asked May 03 '11 01:05

PeterM


People also ask

What returns the characters in the string in reverse order?

With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.

How do you sort a string in reverse order in Python?

To reverse a sorted string in Python, use the sorted() and join() function to pass the one more argument to the sorted() function, which is reverse = True, and it will return the sorted string in reverse order.

How do you reverse the order of a character in Python?

When you're slicing a Python string, you can use the [::-1] slicing sequence to create a reversed copy of the string. This syntax retrieves all the characters in a string and reverses them.


1 Answers

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.

like image 99
Greg Hewgill Avatar answered Sep 21 '22 01:09

Greg Hewgill