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

前端 未结 19 825
名媛妹妹
名媛妹妹 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:21
    #Think about how index works with string in Python,
    >>> a = "123456"
    >>> a[::-1]
    '654321'
    
    0 讨论(0)
  • 2020-11-30 07:22

    Like so:

    >>> s = "2143658709"
    >>> ''.join([s[i+1] + s[i] for i in range(0, len(s), 2)])
    '1234567890'
    
    >>> s = "badcfe"
    >>> ''.join([s[i+1] + s[i] for i in range(0, len(s), 2)])
    'abcdef'
    
    0 讨论(0)
  • 2020-11-30 07:23
    re.sub(r'(.)(.)',r"\2\1",'abcdef1234')
    

    However re is a bit slow.

    def swap(s):
        i=iter(s)
        while True:
            a,b=next(i),next(i)
            yield b
            yield a
    
    ''.join(swap("abcdef1234"))
    
    0 讨论(0)
  • 2020-11-30 07:24

    One of the easiest way to swap first two characters from a String is

    inputString = '2134'
    
    extractChar = inputString[0:2]
    swapExtractedChar = extractChar[::-1]          """Reverse the order of string"""
    swapFirstTwoChar = swapExtractedChar + inputString[2:]
     
    # swapFirstTwoChar = inputString[0:2][::-1] + inputString[2:]     """For one line code"""
    
    print(swapFirstTwoChar)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-30 07:27

    While the above solutions do work, there is a very simple solution shall we say in "layman's" terms. Someone still learning python and string's can use the other answers but they don't really understand how they work or what each part of the code is doing without a full explanation by the poster as opposed to "this works". The following executes the swapping of every second character in a string and is easy for beginners to understand how it works.

    It is simply iterating through the string (any length) by two's (starting from 0 and finding every second character) and then creating a new string (swapped_pair) by adding the current index + 1 (second character) and then the actual index (first character), e.g., index 1 is put at index 0 and then index 0 is put at index 1 and this repeats through iteration of string.

    Also added code to ensure string is of even length as it only works for even length.

    DrSanjay Bhakkad post above is also a good one that works for even or odd strings and is basically doing the same function as below.

    string = "abcdefghijklmnopqrstuvwxyz123"
    
    # use this prior to below iteration if string needs to be even but is possibly odd
    if len(string) % 2 != 0:
        string = string[:-1]
    
    # iteration to swap every second character in string
    swapped_pair = ""
    for i in range(0, len(string), 2):
        swapped_pair += (string[i + 1] + string[i])
    
    # use this after above iteration for any even or odd length of strings
    if len(swapped_pair) % 2 != 0:
        swapped_adj += swapped_pair[-1]
    
    print(swapped_pair)
    
    badcfehgjilknmporqtsvuxwzy21 # output if the "needs to be even" code used
    badcfehgjilknmporqtsvuxwzy213 # output if the "even or odd" code used
    
    0 讨论(0)
提交回复
热议问题