凯撒的密码功能

时间:2012-09-25 18:41:31

标签: python

我试图使用python创建一个凯撒的密码,这就是我能得到多远:

alphabet = ['abcdefghijklmnopqrstuvwxyz']

def create(shift):
    dictionary={}
    emptylist=[]
    int(shift)
    for x in alphabet:
        emptylist.append(x)
        code = ""
        for letters in emptylist:
            code = code + chr(ord(letters) + shift)
            dictionary[letters]=code
    return dictionary

它让我输入我的移位值,然后打印:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    create(2)
  File "C:/Users/Pete/Documents/C- Paisley/A-Level/Computing/dictionarytolist.py", line 11, in create
    code = code + chr(ord(letters) + shift)
TypeError: ord() expected a character, but string of length 26 found

最终产品应该是打印移位的字母。

2 个答案:

答案 0 :(得分:2)

更简单的方法是


def create(shift):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    return alphabet[shift:] + alphabet[:shift]

答案 1 :(得分:1)

您可以尝试将此代码用于您的密码。关于如何使用它应该是相当自我解释的。

>>> UPPER, LOWER = ord('A'), ord('a')
>>> def encode(text, shift):
    data = list(text)
    for i, c in enumerate(data):
        if c.isalpha():
            base = UPPER if c.isupper() else LOWER
            data[i] = chr((ord(c) - base + shift) % 26 + base)
    return ''.join(data)

>>> def decode(text, shift):
    return encode(text, -shift)

>>> encode('This is a test.', 0)
'This is a test.'
>>> encode('This is a test.', 1)
'Uijt jt b uftu.'
>>> encode('This is a test.', 2)
'Vjku ku c vguv.'
>>> encode('This is a test.', 26)
'This is a test.'
>>> encode('This is a test.', 3)
'Wklv lv d whvw.'
>>> decode(_, 3)
'This is a test.'
>>>