首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >编码/解码Caesar密码Python 3 ASCII

编码/解码Caesar密码Python 3 ASCII
EN

Stack Overflow用户
提问于 2017-09-07 22:57:15
回答 1查看 4.2K关注 0票数 0

我正在通过John Zelle写的“计算机科学入门”这本书学习编程。我坚持练习5.8。我需要以某种方式修改这个解决方案,其中"z“后面的下一个字符是"a”,以便使其循环。任何帮助都是非常好的:)

代码语言:javascript
复制
def main():
    print("This program can encode and decode Caesar Ciphers") #e.g. if key value is 2 --> word shifted 2 up e.g. a would be c
    #input from user
    inputText = input("Please enter a string of plaintext:").lower()
    inputValue = eval(input("Please enter the value of the key:"))
    inputEorD = input("Please enter e (to encrypt) or d (to decrypt) ")
    #initate empty list
    codedMessage = ""

    #for character in the string
    if inputEorD == "e":
        for ch in inputText:
            codedMessage += chr(ord(ch) + inputValue) #encode hence plus
    elif inputEorD =="d":
            codedMessage += chr(ord(ch) - inputValue) #decode hence minus
    else:
        print("You did not enter E/D! Try again!!")
    print("The text inputed:", inputText,  ".Is:", inputEorD, ".By the key of",inputValue, ".To make the message", codedMessage)

main()
EN

回答 1

Stack Overflow用户

发布于 2017-09-07 23:10:57

由于您正在处理.lower()-case letters,因此很容易知道它们的ASCII码范围是97-122。

做移位循环的一个好方法是用0-25的范围来表示每个字母,这是由ord(ch) - 97完成的,然后添加键,然后将结果与26取模,这样它就变成了(ord(ch) - 97 + key)%26,然后我们就得到了0-25的结果,加上97就得到了它的ASCII码:

代码语言:javascript
复制
def main():
    print("This program can encode and decode Caesar Ciphers")
    inputText = input("Please enter a string of plaintext:").lower()
    inputValue = int(input("Please enter the value of the key:")) # use int(), don't eval unless you read more about it
    inputEorD = input("Please enter e (to encrypt) or d (to decrypt) ")
    codedMessage = ""

    if inputEorD == "e":
        for ch in inputText:
            codedMessage += chr((ord(ch) - 97 + inputValue)%26 + 97)
    elif inputEorD =="d":
            codedMessage += chr((ord(ch) - 97 - inputValue)%26 + 97)
    else:
        print("You did not enter E/D! Try again!!")
    print("The text inputed:", inputText,  ".Is:", inputEorD, ".By the key of",inputValue, ".To make the message", codedMessage)

main()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46099533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档