Here is the approach re
:
x = 'abcde'
[re.sub(f'(.)(.)(?=.{{{i}}}$)', "\\2\\1", x) for i in reversed(range(len(x)-1))]
And an option that skips double characters:
x = 'abbde'
[s for s, i in (re.subn(f'(.)(?!\\1)(.)(?=.{{{i}}}$)', "\\2\\1", x) for i in reversed(range(len(x)-1))) if i]
source
share