How to undo a string with a step using Python String slicing

I need to flip an alternating line, so I have 2 pairs that should be messed up as follows:

>>> interleaved = "123456"

reversal

>>> print interleaved[::-1]
654321

but i really want

563412

is there a row section operation for this?

+4
source share
3 answers

For long-length strings, this should do this:

>>> s = "123456"
>>> it = reversed(s)
>>> ''.join(next(it) + x for x in it)
'563412'

For strings with odd lengths, you must add 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'

Use of shearing 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'
+7
source

The shortest way, as far as I know, is to use a regex:

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

, .

+4

You can bring some ideas to split the line in parts , and then undo each part and reassemble (merge) the list, which has also changed.

eg. (using satomacoto's answer in an unreadable way)

''.join([a[::-1][i:i+2][::-1] for i in range(0, len(a), 2)]) 

or (using FJ's answer)

''.join(map(''.join, zip(*[iter(a)]*2))[::-1])

etc. (Be ayour line).

+3
source

All Articles