I need to reverse an interleaved string, means i have 2-pairs which shouldt get messed up like this:
>>> interleaved = "123456"
reversing
>>> print interleaved[::-1]
654321
but what i actually want is
563412
is there a string slice operation for this?
For even length strings this should do it:
>>> s = "123456"
>>> it = reversed(s)
>>> ''.join(next(it) + x for x in it)
'563412'
For odd length strings, you need to prepend the first character separately:
>>> s = "7123456"
>>> it = reversed(s)
>>> (s[0] if len(s)%2 else '') + ''.join(next(it) + x for x in it)
'7563412'
Using slicing and zip
:
>>> s = "7123456"
>>> (s[0] if len(s)%2 else '') + ''.join(x+y for x, y in zip(s[-2::-2], s[::-2]))
'7563412'
The shortest way as far as I know would be to use a regex:
import re
''.join(re.findall('..?', '123456', flags=re.S)[::-1])
This also works for odd-length strings without having to implement separate logic for them.
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