Python ValueError: chr() arg not in range(0x110000)

Python ValueError: chr() arg not in range(0x110000)

import enchant
message_decrypt= input("Enter the message you want to decrypt: ")
key= 0
def caesar_hack(message_decrypt,key):
    final_message=""
    d= enchant.Dict("en.US")
    f= d.check(message_decrypt)
    while f== False:
        for characters in message_decrypt:
            if ord(characters)<=90:
                if ord(characters)-key<ord("A"):
                    final_message= final_message+ chr(ord(characters)-key)
                else:
                    final_message= final_message+ chr(ord(characters)-key+26)
            else:
                if ord(characters)-key<ord("a"):
                    final_message=final_message+chr(ord(characters)-key)
                else:
                    final_message= final_message+chr(ord(characters)-key+26)
        key=key+1
        f= d.check(message_decrypt)
    else:
        print(final_message)
caesar_hack(message_decrypt, key)

为什么这段代码不起作用? 我正在尝试使用蛮力技术进行凯撒密码破解。我收到如下错误

有人可以帮助修复此代码。

为了让您的代码正常工作,我必须进行一些调整,这是一个有效的版本:

import enchant
message_decrypt= input("Enter the message you want to decrypt: ")
key= 0
def caesar_hack(message_decrypt,key):
    final_message=""
    d= enchant.Dict("en.US")
    f= d.check(message_decrypt)
    while f== False:
        for characters in message_decrypt:
            if ord(characters)<=90:
                if ord(characters)-key<ord("A"):
                    final_message= final_message+ chr(ord(characters)-key+26)  # The additional 26 should be here, not below
                else:
                    final_message= final_message+ chr(ord(characters)-key)
            else:
                if ord(characters)-key<ord("a"):
                    final_message=final_message+chr(ord(characters)-key+26)  # The additional 26 should be here, not below
                else:
                    final_message= final_message+chr(ord(characters)-key)
        key=key+1
        f= d.check(final_message)  # Check should be on final_message, not message_decrypt
        if not f:
            final_message = ""  # Need to reset the final_message if not matched
    else:
        print(final_message)
caesar_hack(message_decrypt, key)

我已经评论了我所做的主要更改。一个关键是检查循环中的 final_message,而不是 message_decrypt(如果不匹配则为下一个循环再次重置它)。

另一个是如果 26 字符序号超出范围,则需要将其添加到字符序号中。如果不这样做,它会生成 non-printable 个字符,因此检查失败并出现附魔错误。