我正在积极学习Python(3.5)并非常喜欢它。在
我想熟悉字符串操作,因此决定制作一个基本的加密/解密器,它将字符串在字母表中向前移动一个。在
代码如下:def encrypt(string):
string = string.replace('z', 'a')
string = string.replace('y', 'z')
string = string.replace('x', 'y')
string = string.replace('w', 'x')
string = string.replace('v', 'w')
string = string.replace('u', 'v')
string = string.replace('t', 'u')
string = string.replace('s', 't')
string = string.replace('r', 's')
string = string.replace('q', 'r')
string = string.replace('p', 'q')
string = string.replace('o', 'p')
string = string.replace('n', 'o')
string = string.replace('m', 'n')
string = string.replace('l', 'm')
string = string.replace('k', 'l')
string = string.replace('j', 'k')
string = string.replace('i', 'j')
string = string.replace('h', 'i')
string = string.replace('g', 'h')
string = string.replace('f', 'g')
string = string.replace('e', 'f')
string = string.replace('d', 'e')
string = string.replace('c', 'd')
string = string.replace('b', 'c')
string = string.replace('a', 'b')
return string
def decrypt(string):
string = string.replace('b', 'a')
string = string.replace('c', 'b')
string = string.replace('d', 'c')
string = string.replace('e', 'd')
string = string.replace('f', 'e')
string = string.replace('g', 'f')
string = string.replace('h', 'g')
string = string.replace('i', 'h')
string = string.replace('j', 'i')
string = string.replace('k', 'j')
string = string.replace('l', 'k')
string = string.replace('m', 'l')
string = string.replace('n', 'm')
string = string.replace('o', 'n')
string = string.replace('p', 'o')
string = string.replace('q', 'p')
string = string.replace('r', 'q')
string = string.replace('s', 'r')
string = string.replace('t', 's')
string = string.replace('u', 't')
string = string.replace('v', 'u')
string = string.replace('w', 'v')
string = string.replace('x', 'w')
string = string.replace('y', 'x')
string = string.replace('z', 'y')
string = string.replace('a', 'z')
return string
choice = input('Do you want to decrypt or encrypt a sentence? (d / e)')
question = 'Give me a sentence to %s\n'
if choice == 'd':
encrypted_str = input(question % 'decrypt')
decrypted_str = decrypt(encrypted_str)
print(decrypted_str)
elif choice == 'e':
plaintext = input(question % 'encrypt')
encrypted_str = encrypt(plaintext)
print(encrypted_str)
else:
print('That is not a valid option')
我知道这不是你应该怎么做,但我不知道其他的方法。在
我遇到的问题是,如果我尝试加密'zaaz',它会给我'bbbb'而不是'abba'。我知道我的错在哪里(“z”被替换为“a”,“a”替换为“b”),以及它是什么,但不知道如何修复它。有人能给我一个更好的方法吗。在
另外,我看到有人用模运算符将字母表作为字符串进行文本换行或字符串索引,但我不知道如何在这里实现它。在
有什么建议吗?在