简单的密码不工作索引bc?

时间:2017-08-17 20:39:47

标签: python encryption indexing typeerror

我正在尝试编写一个简单的密码,使用两个字母表的字典,我不断收到错误“TypeError:string indices必须是整数”。如何索引c ??

的值
cipher_alphabet = dict(zip('abcdefghijklmnopqrstuvwxyz',
'phqgiumeaylnofdxjkrcvstzwb'))

def cipher(text, cipher_alphabet, option='encipher'):
    result = ""
    for c in text:
        if c in cipher_alphabet:
            result = result + cipher_alphabet[c]
        else:
            result = result + c
    print(ciphertext)

2 个答案:

答案 0 :(得分:0)

一旦我更换了"密文"用"结果":

>>> cipher_alphabet = dict(zip('abcdefghijklmnopqrstuvwxyz',
'phqgiumeaylnofdxjkrcvstzwb'))

>>> def cipher(text, cipher_alphabet, option='encipher'):
    result = ""
    for c in text:
        if c in cipher_alphabet:
            result = result + cipher_alphabet[c]
        else:
            result = result + c
    print result


>>> cipher("bloo",cipher_alphabet)
hndd

答案 1 :(得分:0)

因此将ciphertext修改为result会使其有效,但还有其他方法可以做到这一点,例如使用dict.get()使用默认值:

def cipher(text, cipher_alphabet, option='encipher'):
    return ''.join(cipher_alphabet.get(c, c) for c in text)

>>> cipher('hello world', cipher_alphabet)
einnd tdkng

使用str.maketrans

cipher_alphabet = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'phqgiumeaylnofdxjkrcvstzwb')

def cipher(text, cipher_alphabet, option='encipher'):
    return text.translate(cipher_alphabet)

>>> cipher('hello world', cipher_alphabet)
einnd tdkng