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.
With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With