Python 如何通过字符串获取到chr的代码?
我正在写密码。当查看我的代码时,您可以看到def xor代码,但我需要它处理字符串中的几个字母,但它一直说它不能这样做,因为有多个字母在执行chr函数Python 如何通过字符串获取到chr的代码?,python,python-3.x,Python,Python 3.x,我正在写密码。当查看我的代码时,您可以看到def xor代码,但我需要它处理字符串中的几个字母,但它一直说它不能这样做,因为有多个字母在执行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
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))
我收到一个键入错误。如果要循环关键字的字符,可以使用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)))
你可以提供整个程序,或者给我们一个例子,说明一个键和你输入的数据,以及你得到的结果和你期望的结果。如果name\uuu==\ uuuuu main:输入要解码的字符串后,用户需要输入一个将在字符串中或不在字符串中的单词。stringtodecode=inputMessage要解码:key=InputKeyword:def encodestringtodecode,key:encoded=对于stringtodecode中的字符:encoded=encoded+xorcharacter,key return encoded请不要将其作为注释发布;在您的问题中包含整个代码,并将我提到的其他项目添加到您的问题中,以便我们可以帮助您:您当前的xor适用于单个字符的键。对于密钥中的多个字符,您希望做什么还不清楚。您是否打算在输入中每个字符只使用一个关键字母?您如何处理比密钥更长的消息?关键字母循环吗?我正在尝试,当我尝试时,它打印在一行上。关于如何正确设置它有什么建议吗?我刚刚修复了一个输入错误stringtoencode而不是stringtodecode,但除此之外,我的测试中一切都正常。我想指出的是,在某些情况下,您的加密方案可能会导致打印出控制字符,这并不理想,它可能会破坏您的终端,但如果您仔细选择您的消息和密钥,我建议一个只使用大写字母,另一个全使用小写字母,应该可以工作。