Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse string with stride via Python String slicing

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?

like image 429
Maximilian Körner Avatar asked Dec 08 '22 10:12

Maximilian Körner


2 Answers

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'
like image 182
Ashwini Chaudhary Avatar answered Dec 10 '22 22:12

Ashwini Chaudhary


The shortest way as far as I know would be to use a regex:

import re
''.join(re.findall('..?', '123456', flags=re.S)[::-1])
  • Input: '123456'
  • Output: '563412'

This also works for odd-length strings without having to implement separate logic for them.

like image 37
Qantas 94 Heavy Avatar answered Dec 10 '22 23:12

Qantas 94 Heavy