简体   繁体   中英

Swapping every second character in a string in Python

I have the following problem: I would like to write a function in Python which, given a string , returns a string where every group of two characters is swapped .

For example given "ABCDEF" it returns "BADCFE".

The length of the string would be guaranteed to be an even number.

Can you help me how to do it in Python?

To add another option:

>>> s = 'abcdefghijkl'
>>> ''.join([c[1] + c[0] for c in zip(s[::2], s[1::2])])
'badcfehgjilk'
import re
print re.sub(r'(.)(.)', r'\2\1', "ABCDEF")
from itertools import chain, izip_longest

''.join(chain.from_iterable(izip_longest(s[1::2], s[::2], fillvalue = '')))

You can also use islice s instead of regular slices if you have very large strings or just want to avoid the copying.

Works for odd length strings even though that's not a requirement of the question.

这是另一个简单的解决方案:

"".join([(s[i:i+2])[::-1]for i in range(0,len(s),2)])

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), eg, 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.

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

Here's a nifty solution:

def swapem (s):
    if len(s) < 2: return s
    return "%s%s%s"%(s[1], s[0], swapem (s[2:]))

for str in ("", "a", "ab", "abcdefgh", "abcdefghi"):
    print "[%s] -> [%s]"%(str, swapem (str))

though possibly not suitable for large strings :-)

Output is:

[] -> []
[a] -> [a]
[ab] -> [ba]
[abcdefgh] -> [badcfehg]
[abcdefghi] -> [badcfehgi]

如果您更喜欢单线:

''.join(reduce(lambda x,y: x+y,[[s[1+(x<<1)],s[x<<1]] for x in range(0,len(s)>>1)]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM