Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/5864271/reverse-a-string-in-python-two-characters-at-a-time-network-byte-order

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...