我正在尝试解码加密消息'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()
返回该项在列表中第一次出现的索引。因此表达式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 =''
。不要将字符串与
x = x + 'something new'
连接。继续将每个元素附加到列表中,然后使用str.join()
:# before the loop: clean_text = [] # empty list # inside the loop: clean_text.append(plain[plain.index(cipher[(ord(i)-ord('a'))])]) # later, after the loop, put: ''.join(clean_text)