首页 > 解决方案 > 如何通过字符串获取 chr 的代码?

问题描述

我正在编写用于密码的代码。查看我的代码时,您可以看到该 defxor()代码,但我需要它来处理字符串中的多个字母,但它一直说它不能这样做,因为有多个字母在执行该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))

我得到一个TypeError.

标签: pythonpython-3.x

解决方案


如果要循环关键字的字符,可以使用itertools.cycleandzip将其作为循环消息中字符的一部分:

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)))

推荐阅读