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

前端 未结 19 826
名媛妹妹
名媛妹妹 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:29
    def revstr(a):
        b=''
        if len(a)%2==0:
            for i in range(0,len(a),2):
                b += a[i + 1] + a[i]
            a=b
        else:
            c=a[-1]
            for i in range(0,len(a)-1,2):
                b += a[i + 1] + a[i]
            b=b+a[-1]
            a=b
        return b
    a=raw_input('enter a string')
    n=revstr(a)
    print n
    
    0 讨论(0)
提交回复
热议问题