Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping every second character in a string in Python

I have the following problem: I would like to write a function in Python which, given a string, returns a string where every group of two characters is swapped.

For example given "ABCDEF" it returns "BADCFE".

The length of the string would be guaranteed to be an even number.

Can you help me how to do it in Python?

like image 719
lava Avatar asked Dec 21 '25 06:12

lava


1 Answers

To add another option:

>>> s = 'abcdefghijkl'
>>> ''.join([c[1] + c[0] for c in zip(s[::2], s[1::2])])
'badcfehgjilk'
like image 164
jro Avatar answered Dec 22 '25 20:12

jro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!