首页 > 解决方案 > Python:如何反转字符串的多个切片操作

问题描述

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

从字符串中取出每个第二个字符,然后是不是每个第二个字符的其他字符,并将它们连接为新字符串。这样做n次!

例如:

"这是一个测试!", 1 -> "hsi etTi sats!" "这是一个测试!", 2 -> "hsi etTi sats!" -> “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) 作为输入,我应该如何操作它以使其恢复为“这是一个测试!”?我知道如何获取列表中的所有其他字符,但你如何将它们放回去。我仍处于学习 Python 的早期阶段,所以我想这是由于我对某些基础知识的知识存在漏洞。

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

您如何操作 a 和 b 以便可以恢复 String?我不确定我是否已经澄清了自己。

提前感谢您的时间。

标签: pythonstring

解决方案


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

  • 当字符数为奇数时会发生什么?zip如果您或map长度不等的序列,最后一个字符将丢失。
  • 那么递归加密呢?

所以这是你的解密功能:

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!

推荐阅读