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

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

    If performance or elegance is not an issue, and you just want clarity and have the job done then simply use this:

    def swap(text, ch1, ch2):
        text = text.replace(ch2, '!',)
        text = text.replace(ch1, ch2)
        text = text.replace('!', ch1)
        return text
    

    This allows you to swap or simply replace chars or substring. For example, to swap 'ab' <-> 'de' in a text:

    _str = "abcdefabcdefabcdef"
    print swap(_str, 'ab','de') #decabfdecabfdecabf
    

提交回复
热议问题