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

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

    A more general answer... you can do any single pairwise swap with tuples or strings using this approach:

    # item can be a string or tuple and swap can be a list or tuple of two
    # indices to swap
    def swap_items_by_copy(item, swap):
       s0 = min(swap)
       s1 = max(swap)
       if isinstance(item,str):
            return item[:s0]+item[s1]+item[s0+1:s1]+item[s0]+item[s1+1:]
       elif isinstance(item,tuple):
            return item[:s0]+(item[s1],)+item[s0+1:s1]+(item[s0],)+item[s1+1:]
       else:
            raise ValueError("Type not supported")
    

    Then you can invoke it like this:

    >>> swap_items_by_copy((1,2,3,4,5,6),(1,2))
    (1, 3, 2, 4, 5, 6)
    >>> swap_items_by_copy("hello",(1,2))
    'hlelo'
    >>> 
    

    Thankfully python gives empty strings or tuples for the cases where the indices refer to non existent slices.

提交回复
热议问题