I want to swap each pair of characters in a string. '2143'
becomes '1234'
, 'badcfe'
becomes 'abcdef'
.
How can I do this in Python?
As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.
oneliner:
>>> s = 'badcfe' >>> ''.join([ s[x:x+2][::-1] for x in range(0, len(s), 2) ]) 'abcdef'
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