如何修改Caesar cipher实现,使输出为单个字符串?
解决凯撒密码加密结果逐字符换行的问题
你的代码现在会把每个加密字符单独换行输出,根源有两个问题,同时还有一个字符索引计算的bug,一起给你修正:
问题分析
encryption变量初始化位置错误:你把encryption = ""放在了for循环内部,每次循环都会清空这个变量,导致只能保存当前单个字符。- print语句位置错误:每次循环都调用
print(encryption),所以每个字符都会单独输出并换行。 - 字符索引计算错误:输入的
text已经转成小写,但你用ord(i) - ord('A')计算索引,小写字母的ASCII码比大写A小,会得到负数,导致加密结果错误。
修改后的代码
print(""" 88 88 "" 88 88 ,adPPYba, 88 8b,dPPYba, 88,dPPYba, ,adPPYba, 8b,dPPYba, a8" "" 88 88P' "8a 88P' "8a a8P_____88 88P' "Y8 8b 88 88 d8 88 88 8PP"""""""" 88 "8a, ,aa 88 88b, ,a8" 88 88 "8b, ,aa 88 `"Ybbd8"' 88 88`YbbdP"' 88 88 `"Ybbd8"' 88 88 88 """) alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) def encrypt(text, shift): encryption = "" # 移到循环外,仅初始化一次 for i in text: i_index = ord(i) - ord('a') # 改用小写a计算索引,匹配输入的小写文本 new_index = (i_index + shift) % 26 new_unicode = new_index + ord('A') # 如需输出小写,此处改为ord('a')即可 new_character = chr(new_unicode) encryption += new_character # 持续累积加密字符 print(encryption) # 循环结束后一次性打印完整字符串 encrypt(text, shift)
修改说明
- 将
encryption = ""移到for循环外部,确保可以持续累积所有加密后的字符。 - 把
print(encryption)移到循环结束后,一次性输出完整的加密字符串,避免逐字符换行。 - 将
ord('A')改为ord('a')计算索引,匹配输入的小写文本,保证索引计算正确。如果需要输出小写结果,把new_unicode = new_index + ord('A')改成ord('a')即可。
内容的提问来源于stack exchange,提问作者DJ MASK
相关产品推荐
相关产品推荐

