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

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

    Here's one way...

    >>> s = '2134'
    >>> def swap(c, i, j):
    ...  c = list(c)
    ...  c[i], c[j] = c[j], c[i]
    ...  return ''.join(c)
    ...
    >>> swap(s, 0, 1)
    '1234'
    >>>
    

提交回复
热议问题