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

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

    #Works on even/odd size strings
    str = '2143657'
    newStr = ''
    for i in range(len(str)//2):
        newStr += str[i*2+1] + str[i*2]
    if len(str)%2 != 0:
        newStr += str[-1]
    print(newStr)
    

提交回复
热议问题