我试图加密一个用户输入信息。
我的代码:
#encrypt
user_input = input ("Enter string: ")
for char in user_input: #for every character in input
cipher_num = (ord(char))+3%26 #using ordinal to find the number
cipher= ''
cipher = chr(cipher_num) # using chr to convert back to a letter
cipher_text = '' #add all values to string
cipher_text = (cipher_text+cipher)
print (cipher_text)
#decrypt
for char in cipher_text: #for every character in the encrpted text
decrypt_num = (ord(char))-3%26
decrypt= ''
decrypt = chr(decrypt_num)
decrypt_text = ''
decrypt_text = (decrypt_text+decrypt)
print(decrypt_text)我收到的输出是-
输入字符串: abc
F
C
为什么它只给出字符串中最后一个字符的加密值?
发布于 2017-03-15 05:08:13
在你的循环中,你有
cipher_text = '' #add all values to string将cipher_text重置为空字符串。您的代码在每个循环中都写着:“空cipher_text并在其中放一个字符”。
您需要将这条线移出for循环。
您的代码应该如下所示:
cipher_text = '' # initialise the string
for char in user_input:
cipher_num = (ord(char))+3%26
cipher= '' # you don't need this line as the next one overwrites the variable
cipher = chr(cipher_num)
cipher_text = cipher_text + cipher
# you can shorten the line above to: cipher_text += cipherdecrypt_text也是如此。
有许多方法可以简化这段代码,并使其更加pythonic,但这是另一个问题:)
https://stackoverflow.com/questions/42801478
复制相似问题