Caesar Cipher Function in Python: Encrypted Strings
When implementing a Caesar Cipher function in Python, a common issue arises where the final encrypted text displays only the last shifted character. To resolve this, it's necessary to understand the issue causing this behavior.
In the provided code, the loop iterates over each character in the plaintext. For alphabetic characters, it shifts the character's ASCII code based on the provided shift value. However, each shifted character is appended to an empty string named cipherText within the loop. As a result, only the last character is displayed as the encrypted text.
To rectify this issue, the ciphertext must be constructed within the loop and returned once all characters have been processed. This can be achieved by modifying the code as follows:
def caesar(plainText, shift):
cipherText = ""
for ch in plainText:
if ch.isalpha():
stayInAlphabet = ord(ch) shift
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
finalLetter = chr(stayInAlphabet)
cipherText = finalLetter
return cipherText
With this modification, the cipherText string is initialized once and all shifted characters are appended to it within the loop. When the function returns, the encrypted string contains all shifted characters, as intended.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3