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

前端 未结 19 955
名媛妹妹
名媛妹妹 2020-11-30 06:25

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

How

19条回答
  •  暖寄归人
    2020-11-30 07:10

    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)

提交回复
热议问题