gpt4 book ai didi

python - Python 2 中的简单替换密码

转载 作者:行者123 更新时间:2023-11-30 23:23:18 25 4
gpt4 key购买 nike

下面的代码将明文消息的每个字母在字母表中移动 2 个位置。问题是这段代码不会在字母 y 和 z 或 Y 和 Z 之后循环回到字母表的开头。我现在一直在尝试修复这个问题。我可以做什么来解决这个问题?

msg = raw_input("any string goes here")

cypher = ""

for a in msg:

cypher = cypher + chr(ord(a) + 2)

print cypher

最佳答案

您可以使用 string 模块创建自己的 ascii 字母表列表。那么您就不必担心 ord 方法涉及的所有其他 unicode 字符。小写 ascii 字母的示例如下:

import string
msg = raw_input("any string goes here")

cypher = ""
#creates a alphabet of lowercase ascii characters
alphabet = string.ascii_lowercase

for a in msg:

cypher = cypher + alphabet[((alphabet.index(a) + 2) % 26)]

print cypher

或者,如果您确实决定使用 ord 方法,您可以使用以下方法:

 cypher = cypher + chr(((ord(a) - 95) % 26) + 97)

为了更好地解释这一点,在 unicode 中,字母表从索引 97(97 =“a”)开始,结束索引为 122(122 =“z”)。因此,通过减去 95,我实际上将字母索引增加了 2。然后为了解决我们使用的开始问题的包装% 26 以便索引始终在 0 到 25 之间。最后我添加了 97,以便索引回到 unicode 字母表的 97 到 122 范围内。

关于python - Python 2 中的简单替换密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24049886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com