凯撒密码(Caesar Cipher)代码小写字母功能失效求助
问题排查与修复:凯撒密码无法正确处理小写字母
你的代码核心问题在于没有区分大小写字母的索引范围:
- 你的
ABCs列表前26位是大写字母(索引0-25),后26位是小写字母(索引26-51) - 加密时统一使用
letter3%26,这会把小写字母的索引(26-51)强制映射到0-25的范围,也就是全部转成了大写字母。比如小写e的索引是30,加1后是31,31%26=5,对应大写F,而不是我们想要的小写f。
修复方案
我们可以通过区分大小写的偏移计算来解决这个问题,下面是更简洁易读的修正代码,同时还优化了非字母字符的处理逻辑:
def caesar_encrypt(message, key): encrypted_chars = [] for char in message: if char.isupper(): # 针对大写字母单独计算偏移 original_index = ord(char) - ord('A') new_index = (original_index + key) % 26 encrypted_chars.append(chr(new_index + ord('A'))) elif char.islower(): # 针对小写字母单独计算偏移 original_index = ord(char) - ord('a') new_index = (original_index + key) % 26 encrypted_chars.append(chr(new_index + ord('a'))) else: # 非字母字符直接保留(比如空格、标点) encrypted_chars.append(char) return ''.join(encrypted_chars) ans = input("Do you wish to encrypt, decrypt or brute force? ") if ans == "encrypt": msg = input("Enter your message: ") key = int(input("Enter the key number (1-26): ")) message_end = caesar_encrypt(msg, key) print(f"Your translated text is: {message_end}")
测试验证
输入消息HelLO、密钥1时,输出结果为IfmMP,完全符合预期:
- 大写
H→I,小写e→f,小写l→m,大写L→M,大写O→P
内容的提问来源于stack exchange,提问作者Krish P
相关产品推荐
相关产品推荐

