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

前端 未结 19 946
名媛妹妹
名媛妹妹 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:19

    The usual way to swap two items in Python is:

    a, b = b, a
    

    So it would seem to me that you would just do the same with an extended slice. However, it is slightly complicated because strings aren't mutable; so you have to convert to a list and then back to a string.
    Therefore, I would do the following:

    >>> s = 'badcfe'
    >>> t = list(s)
    >>> t[::2], t[1::2] = t[1::2], t[::2]
    >>> ''.join(t)
    'abcdef'
    

提交回复
热议问题