我正在尝试解码加密的消息'lmnopqrstuvwxyzabcdefghijk'
。我知道它偏移了11,必须解密'I wtvp olel decfnefcpd lyo lwrzctesxd'
。
这是我到目前为止写的内容:
#enciphered message = 'I wtvp olel decfnefcpd lyo lwrzctenter code hereesxd'
plain = 'abcdefghijklmnopqrstuvwxyz'
#plain Index= 0123456789........25
cipher = 'lmnopqrstuvwxxyzabcdefghijk'
#11 12 13 14 15 16 17 18 19 20 21 22 23 24 25...12345678910
cipher_text = input('Enter enciphered message: ')
clean_text ='I '
for i in cipher_text:
if cipher_text.index(i) != " ":
clean_text = clean_text + plain.index(cipher[(ord(i)-ord('a'))])
else:
clean_text = clean_text + " "
print(clean_text)
当我运行它时:
Enter enciphered message: I wtvp olel decfnefcpd lyo lwrzctesxd
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-97-ac338a9d79fc> in <module>
18 for i in cipher_text:
19 if cipher_text.index(i) != " ":
---> 20 clean_text = clean_text + plain.index(cipher[(ord(i)-ord('a'))])
21 #chr((cipher.index(cipher_text[i]))+ ord('a')) - 11)
22 else:
TypeError: can only concatenate str (not "int") to str
我是Python的新手,我不知道如何解决它。
补充:我要解码的加密消息具有大写字母“ I”以及单词之间的空格,因此我想知道如何同时解码大写字母和小写字母
list.index()
返回index of that item's first occurence in the list。因此,表达式plain.index(cipher[(ord(i)-ord('a'))])
是整数,Python不允许将其添加到字符串中。
您可能希望clean_text是plain
中具有那个索引的元素。因此可以使用标准的list[index]
表示法获取元素:plain[plain.index(...)]
该行现在为:
clean_text = clean_text + plain[plain.index(cipher[(ord(i)-ord('a'))])]
>>> print(clean_text)
I wxxyzabcdefghhijlmnopqrstuv
其他更改/改进:
对于行if cipher_text.index(i) != " ":
,该表达式将永远不会为真,因为list.index()
返回一个整数或ValueError(如果未找到),该值将永远不等于空格" "
。您还已经在循环变量i
中包含要检查的字符。因此可能是:
if i != " ":
cipher
和cipher_text
中可能有错字,字母x
出现了两次。
写您的评论:
它在句子的开头也有大写的“ I”,以及单词之间的空格。 :(
是从循环之前的clean_text ='I '
行开始的。将其更改为clean_text =''
。