我正试图用非复杂的代码做一个基本的Ceaser密码,当我键入类似Go Buy Bread的内容并将移位设置为8或更高时,我会得到一个错误,称为字符串索引超出范围,我不想使用mod(%(。有人能给我一个解决方案吗?
Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 -!?.'
FinalMessage = ''
print("Cipher/Decipher Code")
print("-")
print("This code can encode messages and decode messages.")
while True:
print()
Option = int(input('Type the number 1 to encode your message, number 2 to decode, number 3 to exit: '))
print()
if Option == 1:
Message = list(input("Type the message you want to encode: "))
print()
print("To encode the message type a number between 1 and 26.")
print("The number means how many letters the message will shift.")
Key = int(input("Number: "))
for Cipher in Message:
if Cipher in Alphabet:
Position = Alphabet.find(Cipher)
NewPosition = (Position + Key)
NewCipher = Alphabet[NewPosition]
FinalMessage += NewCipher
else:
FinalMessage += Cipher
print()
print("Encrypted Message: " + FinalMessage)
print()
print("------")
print()
elif Option == 2:
print()
Message = list(input("Type the message you want to decode: "))
print()
print("To decode a message type a number between 1 and 26.")
print("The number means how many letters the message will shift")
Key = int(input("Number: "))
Key = (Key * -1)
for Cipher in Message:
if Cipher in Alphabet:
Position = Alphabet.find(Cipher)
NewPosition = (Position + Key)
NewCipher = Alphabet[NewPosition]
FinalMessage += NewCipher
else:
FinalMessage += Cipher
print()
print("Decrypted Message: " + FinalMessage)
print()
print("------")
print()
FinalMessage = ""
不确定为什么您不想使用%
,这似乎是理想的选择。否则,您将不得不手动检查调整后的索引是否超出字母表的范围,并添加/减去字母表的大小以正确换行。
两种方法是:
# Method 1 (preferred).
NewPosition = (Position + Key) % len(Alphabet)
# Method 2 (ugly and unnecessary).
NewPosition = Position + Key
if NewPosition >= len(Alphabet):
NewPosition -= len(Alphabet)
然而,移位为(正(八的Go Buy Bread
不会给alpha字符带来包装问题,因为所有结果都仍在字符串中。如果你减去八,可能会这样,但我假设你想对明文消息进行编码,而不是解码。
因此,您最好的选择是通过每次在循环中打印Position
和NewPosition
(以及len(Alphabet)
(来开始调试。希望这能告诉你发生了什么。