如何正确使用模数和字符串来翻译密文?
How to use modulo and string correctly to translate a crypted sentence?
我正在 python 从事 codeacademy.com 的项目。我必须使用“凯撒密码”来翻译加密的单词。我已经有了答案,但我不明白。
如下所示:
translated_message += 字母表[(letter_value + 10) % 26]
+10 是为了字母的移位,但为什么要对 26 取模呢?
我测试了一个减法,它也有效。在这两种方式中,我不明白为什么它是必要的以及模数做什么?
感谢您的帮助!
alphabet = "abcdefghijklmnopqrstuvwxyz"
punctuation = ".,?'! "
message = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj!"
translated_message = ""
for letter in message:
if not letter in punctuation:
letter_value = alphabet.find(letter)
translated_message += alphabet[(letter_value + 10) % 26]
else:
translated_message += letter
print(translated_message)
letter_value +10 可以超过字母数组中的索引。 Mod 包装它。 Google“模运算”。
我正在 python 从事 codeacademy.com 的项目。我必须使用“凯撒密码”来翻译加密的单词。我已经有了答案,但我不明白。 如下所示:
translated_message += 字母表[(letter_value + 10) % 26]
+10 是为了字母的移位,但为什么要对 26 取模呢? 我测试了一个减法,它也有效。在这两种方式中,我不明白为什么它是必要的以及模数做什么?
感谢您的帮助!
alphabet = "abcdefghijklmnopqrstuvwxyz"
punctuation = ".,?'! "
message = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj!"
translated_message = ""
for letter in message:
if not letter in punctuation:
letter_value = alphabet.find(letter)
translated_message += alphabet[(letter_value + 10) % 26]
else:
translated_message += letter
print(translated_message)
letter_value +10 可以超过字母数组中的索引。 Mod 包装它。 Google“模运算”。