如何制作密码并加密文本?

时间:2015-11-11 14:41:22

标签: python python-3.x

alphabet = 'abcdefghijklmnopqrstuvwxyz'

message = input('Please insert the message you want to encrypt')

key = input('whay key value do you want in your encyption?')

for m in message:
    if m in alphabet:
        key += alphabet [(alphabet.index(m)+key)%(len(alphabet))]

1 个答案:

答案 0 :(得分:0)

保持原始想法,你相当接近。注意,Python已经保留了一个简单的小写字母列表:

import string

alphabet = string.ascii_lowercase
message = input('Please insert the message you want to encrypt: ')
key = int(input('What key value do you want in your encryption? '))

output = []

for m in message:
    if m in alphabet:
        output.append(alphabet[(alphabet.index(m) + key) % (len(alphabet))])

print(''.join(output))

您需要创建新的输出字符列表,因为无法直接更改原始字符串中的字符。然后可以将此列表连接在一起以显示输出。

例如,这将为您提供以下内容:

Please insert the message you want to encrypt: hello
What key value do you want in your encryption? 3
khoorzruog

请注意,有更有效的方法可以解决此问题,例如使用maketrans