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

问题描述 投票:3回答:5

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

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

例如:

“这是一个考验!”,1 - >“hsi etTi坐着!” “这是一个考验!”,2 - >“hsi etTi坐着!” - >“e as!”

我写的函数是:

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以便可以恢复字符串?我不确定自己是否澄清过。

感谢您提前的时间。

python string
5个回答
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!

1
投票

它只是对字符串的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

1
投票

通过使用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

1
投票

根据您的问题,在我看来,您希望创建一个单独的函数,可用于解密使用您的加密函数加密的字符串。如果是这样,那么可以做类似于以下的事情:

def decrypt(text, n):
  if n <= 0:
    return text
  else:
    num = len(text) // 2
    a = text[:num:]
    b = text[num::]

    answer = "".join(map(lambda x,y: x+y, b, a))
    answer = decrypt(answer, n-1)

    return answer if (len(text) % 2 == 0) else answer + b[-1]

0
投票

你可以使用map来连接ba的元素,这会产生一个长度为2的字符串列表。然后使用join将这些连接成原始字符串:

a = "BDF"
b = "ACE"
s = "".join(map(lambda x,y: x+y, b, a))
© www.soinside.com 2019 - 2024. All rights reserved.