Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to swap each pair of adjoining chars in a string with Python?

Tags:

python

string

I want to swap each pair of characters in a string. '2143' becomes '1234', 'badcfe' becomes 'abcdef'.

How can I do this in Python?

like image 930
cocobear Avatar asked Jan 05 '11 14:01

cocobear


People also ask

How do you interchange two characters in a string?

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.


1 Answers

oneliner:

>>> s = 'badcfe' >>> ''.join([ s[x:x+2][::-1] for x in range(0, len(s), 2) ]) 'abcdef' 
  • s[x:x+2] returns string slice from x to x+2; it is safe for odd len(s).
  • [::-1] reverses the string in Python
  • range(0, len(s), 2) returns 0, 2, 4, 6 ... while x < len(s)
like image 200
Paulo Scardine Avatar answered Sep 27 '22 22:09

Paulo Scardine