Python使用备用字母表加密字符串

时间:2016-07-14 00:54:44

标签: python string encryption

我不确定如何开展这项工作。我需要加密给出不同字母表的字符串。

def substitute(string, ciphertext):
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    encrypted = []
    list(alphabet)
    list(ciphertext)
    encrypted = ""
    for x in string:
        if x.isalpa():
            encrypted.append(ciphertext[x])
        else:
            encrypted.append(x)
            word = string.join(encrypted)
    print(encrypted)

    return encrypted

1 个答案:

答案 0 :(得分:1)

试试这个:

def substitute(string, ciphertext):
    alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") # list() returns a list,
    ciphertext = list(ciphertext) # it doesn't change (mutate) the variable
    encrypted = [] # Not sure why you were storing the empty string here,
                   # but strings cannot use the append() method.
    for x in string:
        if x.isalpha(): # Fixed a typo
            # Here I think you want to use alphabet.index(x) instead of x.
            encrypted.append(ciphertext[alphabet.index(x)])
        else:
            encrypted.append(x)
    return "".join(encrypted) # Turning the list into a string

正如另一位意见提供者所说,将来请添加您的工作示例,而不是您的代码。

我建议查找 可变性 的定义,因为这似乎是您正在努力解决的问题。