我的PythonCaeserCipher程序在30后停止移动
我创建了一个函数来将输入的字符串拆分为单词列表,然后将每个单词中的字母替换为其移位的对应物,但是当我将移位设置为超过 30 时,它的打印结果不变。
def ceaser_cipher_encoder(string , num):
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"]
new_string = ""
string_list = string.split(" ")
new_list = []
for word in string_list:
word1 = ""
for charecter in word:
letter_position = alphabet.index(charecter)
letter_position_with_shift = letter_position + num
if letter_position_with_shift > 25:
letter_position_with_shift = 0 + ((letter_position - 25) - 1)
word1 += charecter.replace(charecter, alphabet[letter_position_with_shift])
new_list.append(word1)
end_string = " ".join(new_list)
return end_string
message = ceaser_cipher_encoder("hello dad", 35)
print(message)
回答
这里的一个有用技巧是使用模运算符 ( %)。它将为您处理班次。
这是我会怎么做:
def ceaser_cipher_encoder(string , num):
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"]
new_string = ""
for c in string:
new_string += alphabet[(alphabet.index(c) + num) % len(alphabet)]
return new_string
假设c是“y”并且num是 10。那么您将alphabet.index(c)等于 24,因此移位将返回 34。由于 34 模 26 是 8,它会将alphabet[8]("i")附加到new_string。
我用len(alphabet)26 代替了硬编码,这样您就可以更改字母表并且代码仍然有效。