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

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

    Loop over length of string by twos and swap:

    def oddswap(st):
        s = list(st)
        for c in range(0,len(s),2):
            t=s[c]
            s[c]=s[c+1]
            s[c+1]=t
    
        return "".join(s)
    

    giving:

    >>> s
    'foobar'
    >>> oddswap(s)
    'ofbora'
    

    and fails on odd-length strings with an IndexError exception.

提交回复
热议问题