简体   繁体   English

在Python中交换字符串中的每第二个字符

[英]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 .我有以下问题:我想在 Python 中编写一个函数,给定一个字符串,返回一个字符串,其中每组两个字符都被交换

For example given "ABCDEF" it returns "BADCFE".例如,给定“ABCDEF”,它返回“BADCFE”。

The length of the string would be guaranteed to be an even number.字符串的长度将保证为偶数。

Can you help me how to do it in Python?你能帮我如何在 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.如果您有非常大的字符串或只想避免复制,您也可以使用islice代替常规切片。

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".仍在学习 Python 和字符串的人可以使用其他答案,但他们并不真正了解它们的工作方式或代码的每一部分在做什么,而没有海报的完整解释,而不是“这个作品”。 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.它只是简单地以二进制(从 0 开始并查找每个第二个字符)遍历字符串(任何长度),然后通过添加当前索引 + 1(第二个字符)和实际索引(第一个)创建一个新字符串(swapped_pa​​ir)字符),例如,将索引 1 放在索引 0 处,然后将索引 0 放在索引 1 处,这通过字符串的迭代重复。

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)]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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