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

前端 未结 19 823
名媛妹妹
名媛妹妹 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
    
    0 讨论(0)
  • 2020-11-30 07:08

    Do you want the digits sorted? Or are you swapping odd/even indexed digits? Your example is totally unclear.

    Sort:

    s = '2143'
    p=list(s)
    p.sort()
    s = "".join(p)
    

    s is now '1234'. The trick is here that list(string) breaks it into characters.

    0 讨论(0)
  • 2020-11-30 07:10

    oneliner:

    >>> s = 'badcfe'
    >>> ''.join([ s[x:x+2][::-1] for x in range(0, len(s), 2) ])
    'abcdef'
    
    • s[x:x+2] returns string slice from x to x+2; it is safe for odd len(s).
    • [::-1] reverses the string in Python
    • range(0, len(s), 2) returns 0, 2, 4, 6 ... while x < len(s)
    0 讨论(0)
  • 2020-11-30 07:11

    One more way:

    >>> s='123456'
    >>> ''.join([''.join(el) for el in zip(s[1::2], s[0::2])])
    '214365'
    
    0 讨论(0)
  • 2020-11-30 07:13
    ''.join(s[i+1]+s[i] for i in range(0, len(s), 2)) # 10.6 usec per loop
    

    or

    ''.join(x+y for x, y in zip(s[1::2], s[::2])) # 10.3 usec per loop
    

    or if the string can have an odd length:

    ''.join(x+y for x, y in itertools.izip_longest(s[1::2], s[::2], fillvalue=''))
    

    Note that this won't work with old versions of Python (if I'm not mistaking older than 2.5).

    The benchmark was run on python-2.7-8.fc14.1.x86_64 and a Core 2 Duo 6400 CPU with s='0123456789'*4.

    0 讨论(0)
  • 2020-11-30 07:16

    Loop over length of string by twos and swap:

    def oddswap(st):
        s = list(st)
        for c in range(0,len(s),2):
            t=s[c]
            s[c]=s[c+1]
            s[c+1]=t
    
        return "".join(s)
    

    giving:

    >>> s
    'foobar'
    >>> oddswap(s)
    'ofbora'
    

    and fails on odd-length strings with an IndexError exception.

    0 讨论(0)
提交回复
热议问题