我正在写密码。在查看我的代码时,您可以看到def xor()
代码,但是我需要它为字符串中的多个字母工作,但是它一直说它不能这样做,因为有多个字母在{ {1}}功能。
chr
我得到一个if __name__=="__main__":
#After the string to decode is input, the user needs to input a word that will or will not be in the string.
stringtodecode = input("Message to Decode: ")
key = input("Key Word: ")
def encrypt(stringtodecode, key):
encrypted = ''
for character in stringtodecode:
encrypted = encrypted + xor(character, key)
return encrypted
def decrypt(stringtodecode, key):
return encrypt(stringtodecode, key)
def xor(character, key):
code = ord(character) ^ ord(key)
character = chr(code)
return character
print(decrypt(stringtodecode, key))
。
答案 0 :(得分:1)
如果您要循环使用关键字的字符,则可以使用itertools.cycle
和zip
来做为循环遍历消息中字符的一部分:
import itertools # put this up near the top of the file somewhere
for m_char, k_char in zip(stringtodecode, itertools.cycle(key)):
encrypted = encrypted + xor(m_char, k_char)
如果字符串可能变长(通过时间与输出长度的平方成正比),则通过重复串联来构建字符串将没有效率(因此,您可能需要在生成器表达式上使用str.join
(它将在线性时间内运行):
encrypted = "".join(xor(m_char, k_char)
for m_char, k_char in zip(stringtodecode, itertools.cycle(key)))