Python:如何反转字符串的多片操作

2024-09-28 05:23:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一个有趣的Python编码问题:

从字符串中每隔2个字符取一个字符,然后取不是每隔2个字符的其他字符,并将它们合并为新字符串。 这样做n次!你知道吗

例如:

“这是个考验!”,1->;“hsi etTi sats!” “这是个考验!”&satetts-&hsi;“2号!”->;“s eT ashi tist!”你知道吗

我写的函数是:

def encrypt(text, n):
    if n <= 0:
        return text
    else:
        a = encrypt(text, n-1)[1::2]
        b = encrypt(text, n-1)[::2]
        return a+b

从一个测试函数的结果来看,这似乎是可行的。但现在我不知道如何逆转这个动作。例如,使用(“hsi etTi sats!”,1)作为输入,我应该如何操作它才能将其还原为“This is a test!”?我知道如何把列表中的其他字符都取出来,但是你怎么把它们放回去。我还处在学习Python的早期阶段,所以我想这是因为我对一些基础知识的理解有漏洞。你知道吗

String = "ABCDEF"
a= String[1::2] = "BDF"
b= String[::2] ="ACE"

如何操作a和b,以便恢复字符串?我不确定我是否已经澄清了自己。你知道吗

谢谢你提前抽出时间。你知道吗


Tags: 字符串textgt编码stringreturn字符et
3条回答

其他一些答案在整个问题中缺少两个重要方面

  • 当字符数为奇数时会发生什么?如果使用长度不等的zipmap序列,则最后一个字符将丢失。你知道吗
  • 递归加密呢?你知道吗

下面是解密函数:

def encrypt(text, n):
    if n <= 0:
        return text
    else:
        a = encrypt(text, n-1)[1::2]
        b = encrypt(text, n-1)[::2]
        return a+b

def decrypt(text, n):
    if n <= 0:
        return text
    else:
        a, b = text[:len(text)//2], text[len(text)//2:]
        text = "".join(map(lambda x, y: x + y, b, a))
        text = decrypt(text, n-1)
        if len(b) > len(a):
            # happens for odd number of characters. We need to append last from b
            text += b[-1]
        return text

s = "This is a test!"

print("n=1: {0}".format(decrypt(encrypt(s, 1), 1)))
print("n=2: {0}".format(decrypt(encrypt(s, 2), 2)))
print("n=3: {0}".format(decrypt(encrypt(s, 3), 3)))

>>> n=1: This is a test!
>>> n=2: This is a test!
>>> n=3: This is a test!

它只是对字符串的zip操作。但是,不能直接使用zip,需要将其格式化为字符串。你知道吗

s = "ABCDEF"
a = s[1::2]
b = s[::2]

print(a,b)

s2 = "".join(["{0}{1}".format(x, y) for (x, y) in zip(b, a)])

print(s2)


>>> BDF ACE
>>> ABCDEF

通过使用zip,您可以同时循环浏览两个列表。通过将end=""添加到print函数,它将继续在同一行打印。你知道吗

这应该起作用:

expression="This is a test!"
first=expression[1::2]
second=expression[::2]

for i,j in zip(first,second):
    print(j+i,end="")

因此,输出为:

This is a test

相关问题 更多 >

    热门问题