首页 > 解决方案 > 我的 Python Caeser Cipher 程序在 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)

标签: pythonencryption

解决方案


这里一个有用的技巧是使用运算符 ( %)。它将为您处理转变。

这是我会怎么做:

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,以便您可以更改字母表并且代码仍然可以使用。


推荐阅读