我正在研究一个有趣的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,以便恢复字符串?我不确定我是否已经澄清了自己。你知道吗
谢谢你提前抽出时间。你知道吗
其他一些答案在整个问题中缺少两个重要方面
zip
或map
序列,则最后一个字符将丢失。你知道吗下面是解密函数:
它只是对字符串的
zip
操作。但是,不能直接使用zip
,需要将其格式化为字符串。你知道吗通过使用
zip
,您可以同时循环浏览两个列表。通过将end=""
添加到print
函数,它将继续在同一行打印。你知道吗这应该起作用:
因此,输出为:
相关问题 更多 >
编程相关推荐