Python中的凯撒密码函数 [英] Caesar Cipher Function in Python

查看:119
本文介绍了Python中的凯撒密码函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Python 中创建一个简单的 Caesar Cipher 函数,该函数根据用户的输入移动字母并在末尾创建一个最终的新字符串.唯一的问题是最终的密文只显示最后一个移位的字符,而不是包含所有移位字符的整个字符串.

I'm trying to create a simple Caesar Cipher function in Python that shifts letters based on input from the user and creates a final, new string at the end. The only problem is that the final cipher text shows only the last shifted character, not an entire string with all the shifted characters.

这是我的代码:

plainText = raw_input("What is your plaintext? ")
shift = int(raw_input("What is your shift? "))

def caesar(plainText, shift): 

    for ch in plainText:
        if ch.isalpha():
            stayInAlphabet = ord(ch) + shift 
            if stayInAlphabet > ord('z'):
                stayInAlphabet -= 26
            finalLetter = chr(stayInAlphabet)
        cipherText = ""
        cipherText += finalLetter

    print "Your ciphertext is: ", cipherText

    return cipherText

caesar(plainText, shift)

推荐答案

我意识到这个答案并不能真正回答您的问题,但我认为无论如何它都有帮助.这是使用字符串方法实现凯撒密码的另一种方法:

I realize that this answer doesn't really answer your question, but I think it's helpful anyway. Here's an alternative way to implementing the caesar cipher with string methods:

def caesar(plaintext, shift):
    alphabet = string.ascii_lowercase
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    table = string.maketrans(alphabet, shifted_alphabet)
    return plaintext.translate(table)

事实上,由于字符串方法是用 C 实现的,我们会看到这个版本的性能有所提高.这就是我认为的pythonic"方式.

In fact, since string methods are implemented in C, we will see an increase in performance with this version. This is what I would consider the 'pythonic' way of doing this.

这篇关于Python中的凯撒密码函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆