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

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

提交回复
热议问题